2016-12-14 75 views
1

我有这个简单的代码,我知道我必须做一些愚蠢的错误:Unique_copy没有返回预期的输出

#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本身的定义。

是否有任何功能可以做我所期望的(删除独立元素而不考虑邻接关系),除了在ordered set中插入它们或在唯一副本之前进行排序,因为我想保留排序。

+0

你原来问题的答案,我会建议您为您的跟进问题,一个新的职位(除非已在SO上存在一个)。 – user2079303

回答

2

std::unique_copy

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

one在你的情况下是不连续的。

尝试:

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

,你会发现在输出

- one - two - three - four - - 
+0

是啊,它是“一个”不相邻。该死的 !! – instance