end_unique算法,元素消失

end_unique algorithm, element disappear

#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;
}

-- 结果:

hi hi horrible love love peace peace

hi horrible love peace love  peace

hi horrible love peace

end_unique算法不删除元素。 但在第二次 cout 操作时,“hi”消失了。 为什么“嗨”在第二行消失了?

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

[end_unique, words.end()) 中的任何项目在调用 std::unique 后都具有未指定的值。这就是为什么“擦除”范围内的输出看起来很奇怪。

如果您想保留“已擦除”的单词并保持相对顺序,std::stable_partition with the appropriate lambda 可以检查重复项。