Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

c++11 - C++ std::unique is not showing what I am expecting from it

I was trying to find if the vector contains duplicates (please don't provide an algorithm to check duplicates.) I came up with this weird behavior. std::unique on vector 1,2,3,1 should make it 1,2,3,1 returning an iterator to 1 but on erasing the iterator returned till the vector.end() I got the same size vector as that of I original vector. Here is the snippet of code depicting the said behavior (available at ideone)

    vector<int> nums2 = {1,2,3,4};  
    vector<int> nums = {1,2,3,1};
    cout << "nums1" << endl;
    vector<int> a(nums.begin(), nums.end());
    auto ip = unique(nums.begin(), nums.begin()+nums.size());
    nums.resize( std::distance(nums.begin(),ip) );
    cout << a.size() <<  " " << nums.size() << endl;

    cout << "Nums2" << endl;
    vector<int> a2(nums2.begin(), nums2.end());
    auto ip2 = unique(nums2.begin(), nums2.begin()+nums2.size());
    nums.resize( std::distance(nums2.begin(),ip2) );
    cout << a2.size() <<  " " << nums2.size();

The actual output is

nums1
4 4
Nums2
4 4

but it should have been

nums1
4 3
Nums2
4 4
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

std::unique only removes consecutive duplicates. From cppreference.com on std::unique :

Eliminates all but the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.

Your 1s are not consecutive so they aren't removed. This is the expected behavior. A quick solution is to first std::sort your range.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...