简体   繁体   中英

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. 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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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