MENU

【模板】元素去重

March 30, 2023 • 算法

元素去重在编程中非常重要,我们能可以有多种方式进行去重

1.利用std::unique函数进行去重

在使用 unique 函数去重之前,我们需要先对元素进行排序,然后执行去重

std::unique 函数在 algorithm 头文件中,记得导入
#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> lst = {1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8, 9};

    sort(lst.begin(), lst.end());
    lst.erase(unique(lst.begin(), lst.end()), lst.end());

    for (auto i : lst) {
        cout << i << " ";
    }
    cout << endl;
  
    return 0;
}

这种去重的方法,除了 vector可以使用以外,string也可以正常工作

#include <algorithm>
#include <string>
#include <iostream>

using namespace std;

int main() {
    string str = "hello";

    sort(str.begin(), str.end());
    str.erase(unique(str.begin(), str.end()), str.end());
    cout << str << endl;
    
    return 0;
}

2.利用std::set特性去重

众所周知,set 容器的特点就是没有重复的元素,我们可以尝试将 vector 转换为 set,再转换回 set,从而实现去重操作

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

using namespace std;

int main() {
    vector<int> lst = {1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8, 9};

    set<int> st(lst.begin(), lst.end());
    lst.assign(st.begin(), st.end());

    for (auto i : lst) {
        cout << i << " ";
    }
    cout << endl;
  
    return 0;
}

两种代码量都差不多,不过建议使用第一种。

作者:NorthCity1984
出处:https://grimoire.cn/algorithm/unique.html
版权:本文《【模板】元素去重》版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任