Home > database >  end_unique algorithm, element disappear
end_unique algorithm, element disappear

Time:04-12

#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <iterator>
#include <algorithm>
using namespace std;

void elimdups(vector<string>& words) {
    sort(words.begin(), words.end());
    for(auto a : words)
    {
        cout << a << " ";
    }
    cout << endl;
    auto end_unique = unique(words.begin(), words.end());
    for (auto a : words)
    {
        cout << a << " ";
    }
    cout << endl;
    words.erase(end_unique, words.end());
    for (auto a : words)
    {
        cout << a << " ";
    }
    cout << endl;
}


int main()
{
    vector<string> kim = { "love", "peace", "horrible", "love", "peace", "hi", "hi" };
    elimdups(kim);

    return 0;
}

-- result:

hi hi horrible love love peace peace

hi horrible love peace love  peace

hi horrible love peace

end_unique algorithm do not delete elements. but on the second cout operation, "hi" disappear. why "hi" disappear on the second line?

CodePudding user response:

auto end_unique = unique(words.begin(), words.end()); 
for (auto a : words)
//...

Any items from [end_unique, words.end()) have unspecified values after the call to std::unique. That's why the output in the "erased" range seems strange.

If you want to preserve the "erased" words and keep the relative order, std::stable_partition with the appropriate lambda that checks duplicates could have been done.

  • Related