2016-12-14 72 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