Quick question (hopefully). I have a vector of strings and need to remove duplicates. Normally, I'd just use sort, erase and unique. However, I don't want to sort the data. My idea was to copy the vector to a set, then back to a vector. But every attempt just screws up the order. My last attempt involved copying the vector to a set, copying the set to another vector by using back_insert, and then reversing the vector. Doesn't work. I'd appreciate any ideas on how to solve this. Thanks. Here's the last attempt:

copy(v.begin(), v.end(), inserter(s, s.end()));
copy(s.begin(),s.end(), back_inserter(newV));
reverse(newV.begin(),newV.end());

Recommended Answers

All 4 Replies

You can't copy it to a set and back again without breaking the order.
Sets store on a compiler defined manor but normally red-black trees.
Hence you will destroy the order.

The easiest way is to copy to another vector sort, unique
and then find the copies.

Another slightly more involved way is to copy to a map in which you have the positions in the vector as the second component. The remove the clashes. Depending on the vector type a hash map may work better.

commented: thanks for the help +2

Here's a function that uses a set to remove duplicates from a vector without changing the order of elements:

void remove_dups (vector<string>& v) {
    set<string> s;
    pair<set<string>::iterator, bool> result;

    for (vector<string>::iterator i = v.begin(); i < v.end(); ++i) {

        result = s.insert(*i);

        if (!result.second) {
            v.erase(i);
            --i;  // adjust iterator
        }
    }
}

I'm not sure if the --i can blow up (although note that the first element will never be erased because it definitely will not be in the set).

commented: thanks for the help +2
Member Avatar for jencas

erase() invalidates the iterator passed, but it returns a valid iterator. Just change the code to:

i = v.erase(i);
commented: thanks for the help +2

Big thanks to all three of you. Got it working.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.