一、去重的原理
C++標準庫中的unique算法可以去除相鄰的重複元素,這種去重的原理是依次檢查相鄰兩個元素是否相等,如果相等就刪除後面的元素,直到檢測完所有元素為止。unique算法並沒有改變容器中的大小,同時返回去重後的尾指針,可以通過該指針得知去重後容器中元素的個數。
二、不同容器的用法
1. vector
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector v = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
auto it = unique(v.begin(), v.end());
v.erase(it, v.end());
for(auto i : v)
cout << i << " ";
return 0;
}
上述代碼構造了一個vector,然後調用unique算法,實現了去重操作,最後輸出去重後的vector元素。
2. list
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
list l = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
l.unique();
for(auto i : l)
cout << i << " ";
return 0;
}
list的去重操作可以在list容器對象上直接調用unique函數實現,這是因為list容器內部實現了去重操作。
3. set
#include <iostream>
#include <set>
using namespace std;
int main()
{
set s = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
for(auto i : s)
cout << i << " ";
return 0;
}
set容器本身就具有去重的功能,重複元素將無法插入到set容器中,因此只需將元素插入set容器中即可實現去重操作。
三、關鍵字去重
以上的去重算法都是比較元素是否相等來進行去重的,然而在關鍵字去重的場景下,會根據元素的某些屬性進行去重。此時需要自定義去重判斷的方法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Person
{
string name;
int age;
bool operator==(const Person &p) const
{
return name == p.name && age == p.age;
}
};
int main()
{
vector<Person> v = {{"張三", 20}, {"李四", 22}, {"張三", 20}, {"王五", 25}, {"李四", 22}};
auto it = unique(v.begin(), v.end(), [](const Person &p1, const Person &p2) {return p1 == p2;});
v.erase(it, v.end());
for(auto i : v)
cout << i.name << " " << i.age << endl;
return 0;
}
上述代碼中自定義了Person結構體,然後在unique算法中使用了lambda表達式,重載了判斷規則,實現了按照Person結構體中的name和age屬性進行去重操作。
四、使用場景
unique算法在實際開發中的使用場景較多,例如:
1.去除重複的網絡請求數據;
2.對算法重複輸出的結果進行去重;
3.多通道信號過濾;
4.等等。
總結
本文詳細介紹了C++標準庫中的unique算法,包括去重原理、在不同容器中的使用以及關鍵字去重方法,同時給出了使用場景。unique算法的使用可以大大簡化代碼,提高開發效率。
原創文章,作者:YFUFA,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/333845.html