更新时间:2023-11-28 23:13:10
在Google中寻找std::unique
,我发现此页面 cplusplus:唯一.我在看
a)它做了什么
Looking in google for std::unique
I found this page cplusplus : unique. I looked at
a) what it did
从每个连续的组中删除除第一个元素外的所有元素
Removes all but the first element from every consecutive group
因此,它看起来像您想要的-删除重复项.
So it looks like it does what you want - removes the duplicates.
然后我查看返回的内容以及遇到问题的一些评论...
I then looks at what it returns, and some comments, coming across a problem...
返回值:对未删除的最后一个元素之后的元素的迭代器.
Return value : An iterator to the element that follows the last element not removed.
因此,unique的结果是一个序列,该序列不必与整个向量相同.
So the result from unique is a sequence which is not necessary the same as the whole vector.
如果未删除任何内容,则返回值将是向量的结尾.
If nothing was removed the return value would be the end of the vector.
所以
vector<int>::iterator it = std::unique( a.begin(), a.end() );
bool wasUnique = (it == a.end() );
或者对于C ++ 11
Or for C++11
auto it = std::unique( a.begin(), a.end() );
bool wasUnique = (it == a.end() );
最后,为使唯一功能正常工作,必须对向量进行排序,因此完整的代码应包含
Finally for the unique function to work, the vector needs to be sorted, so the complete code would include
sort(a.begin(), a.end());
例如
sort(a.begin(), a.end());
auto it = std::unique( a.begin(), a.end() );
bool wasUnique = (it == a.end() );