Unique_copy不返回预期的输出

Unique_copy not returning expected output

本文关键字:输出 返回 copy Unique      更新时间:2023-10-16

我有这个简单的代码,我知道我一定犯了一些愚蠢的错误:

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<iterator>
using namespace std;
int main()
{
vector<string> coll{"one", "two", "two", "three", "four", "one"};
vector<string> col2(coll.size(), "");
unique_copy(coll.cbegin(), coll.cend(), col2.begin());
for(const auto& ele : col2)
cout<<" - "<<ele;
cout<<endl;
return 0;
}

输出 -- one - two - three - four - one -

我期待:-- one - two - three - four - -

我错过了什么?

编辑:正如aswer中指出的那样 - 该死的,我错过了unique_copy本身的定义。

是否有任何功能可以做我期望的ecd(删除唯一元素,无论邻接关系如何),而不是将它们插入ordered set或在唯一副本之前排序,因为我想保持排序。

std::unique_copy :

将元素从范围[first, last)复制到从d_first开始的另一个范围,这样就没有连续的相等元素。

在您的情况下,one不是连续的。

尝试:

vector<string> coll{"one", "one", "two", "two", "three", "four"};

你会发现输出为

- one - two - three - four -  -