gaurab_sust's blog

By gaurab_sust, 10 years ago, In English

Suppose the vector is vec then , vec.sort(vec.begin(),vec.end()); vec.resize(distance(vec.begin(),unique(vec.begin(),vec.end())));

  • Vote: I like it
  • -5
  • Vote: I do not like it

| Write comment?
»
10 years ago, # |
  Vote: I like it 0 Vote: I do not like it

i don't know if this will solve ur problem, but maybe u can try using std::set instead of std::vector.

»
10 years ago, # |
Rev. 2   Vote: I like it +19 Vote: I do not like it

And what's wrong with your solution? I usually use one of these two snippets:

sort(a.begin(), a.end());
a.resize(a.end() - unique(a.begin(), a.end));
sort(a.begin(), a.end());
a.erase(unique(a.begin(), a.end()), a.end());
  • »
    »
    10 years ago, # ^ |
      Vote: I like it +37 Vote: I do not like it

    Isn't your first snippet wrong?

    a.resize(unique(a.begin(), a.end()) - a.begin());
    

    It should be something like this (you've also missed brackets after end).

    • »
      »
      »
      14 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      why we subtract a.begin() ?

      • »
        »
        »
        »
        14 months ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        This function removes all but the first element from every consecutive group of equivalent elements in the range [first,last). It returns an iterator to the element that follows the last element not removed. The range between first and this iterator includes all the elements in the sequence that were not considered duplicates.