avatar
fireworks99
keep hungry keep foolish

c++ unique

unique函数

线段树离散化时用到了unique函数除重,在这里记一下

头文件

algorithm

用法

unique(头地址, 尾地址)返回一个地址,用这个地址 减 头地址得数字“有几种”

int m = unique(vec.begin(), vec.end()) - vec.begin();

unique函数使得 vec前m个元素各不相同,后面的元素保持原来值不变(好多人认为把前面的值后调了)

测试

#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    int a[10] = {20, 20, 20, 10, 10, 30};
    int n = unique(a, a + 10) - a;
    cout << n << '\n';
    for(int i = 0; i < 10; ++i)
        cout << a[i] << ' ';
    cout << '\n';
    ///前n个数字不重复,后面的数字保持为原来的值
    vector<int> vec;
    vec.push_back(20);
    vec.push_back(20);
    vec.push_back(20);
    vec.push_back(10);
    vec.push_back(10);
    vec.push_back(30);
    int m = unique(vec.begin(), vec.end()) - vec.begin();
    cout << m << '\n';
    for(int i = 0; i < vec.size(); ++i)
        cout << vec[i] << ' ';
    cout << '\n';
    return 0;
}

ceshi

Site by Baole Zhao | Powered by Hexo | theme PreciousJoy