Detailed explanation of the unique() function in C++ STL

Detailed explanation of the unique() function in C++ STL

1. Brief description

unique()Function is used to delete the sequence repeats of adjacent elements, attention must be adjacent elements (so the use of unique()pre-function generally need to be sorted), and delete here is not directly delete (will return an iterator, then re-use erase()function delete)

2. Function prototype

iterator unique(iterator it_1,iterator it_2,bool MyFunc);
  • The first two parameters are iterators, which means to [it_1, it_2)de- duplicate the interval (left closed and right open, the same as many other STL functions)
  • The last parameter is a custom function. I don’t need to introduce too much here. You can refer to http://www.cplusplus.com/reference/algorithm/unique/
  • Delete section Note [it_1, it_2)in the repeat of the adjacent elements

3. Principle introduction

In fact, the principle is relatively simple, which is to continuously cover the previous repeated elements with the non-repeated elements, and return the coordinates of the last non-repeated element (iterator)

In fact, it is equivalent to the following code:

iterator My_Unique (iterator first, iterator last)
{
    
    
if (first==last)
    return last;  // 只有一个元素的情况
iterator result = first;  // 从第一个元素开始
while (++first != last)   // 直到最后一个元素
{
    
    
if (*result != *first)    // 找到了一个不重复的元素
	*(++result)=*first;   // 覆盖前面的元素
}
return ++result;          // 返回最后不重复元素的坐标
}

4. Example of use

Use unique()functions for deduplication

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;


int main()
{
    
    
    int myints[] = {
    
    1,2,3,1,1};
    int len = sizeof(myints)/sizeof(int);
    vector<int> vec(myints, myints + len);
    sort(vec.begin(), vec.end());
    vec.erase(unique(vec.begin(), vec.end()), vec.end());
    for(int x : vec)
        cout << x << ",";
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44338712/article/details/107876510