简体   繁体   English

为什么vector.erase会删除所有重复项?

[英]why does vector.erase remove all my duplicates?

I'm trying to delete duplicates of numbers in a vector. 我正在尝试删除向量中的重复数字。 i use this to do that: 我用它来做到这一点:

vec1.erase(   unique(vec1.begin(),vec1.end())   ,vec1.end());

found it with google and it works just fine, my question is WHY? 发现它与谷歌,它的工作得很好,我的问题是为什么? according to what I've read on cplusplus, erase removes from the first parameter to the last. 根据我在cplusplus上读到的内容, erase从第一个参数删除到最后一个参数。 ex: 例如:

vec1.erase(vec1.begin(),vec1.begin()+3);  //removes first 3 elements

and unique returns a pointer to the first duplicate, so in simpler version what I'm writing is: unique返回指向第一个副本的指针,所以在更简单的版本中我写的是:

vec1.erase(first duplicate, vec1.end());

shouldn't my vector end after the first duplicate? 第一次重复后我的矢量不应该结束吗?

std::unique eliminates unique elements in-place and returns a pointer to the resulting end of the range. std::unique在原位消除了唯一元素,并返回指向范围结果的指针。 For example, 例如,

1 2 2 3 3 3
^begin      ^end

becomes

1 2 3 . . . (garbage)
      ^ resulting end

You're thinking of std::adjacent_find , which does return an iterator to the first duplicate element. 您正在考虑std::adjacent_find ,它确实将迭代器返回到第一个重复元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM