C++ 在集合和映射容器中获取唯一值

c++ get unique values in set and map containers

本文关键字:获取 唯一 集合 映射 C++      更新时间:2023-10-16

如何在容器中获取唯一值? 我看到矢量和列表有unique(),但我找不到类似的集合和地图。

UPD:我用它来在容器中生成值。

#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <map>

using namespace std;
template <class T>
void rvec(T& t, int l) {
for (int i = 0; i < l; i++)t.push_back(rand() % 10);
}
template <class T>
void rlist(T &t, int l){
for(int i=0;i<l;i++)t.push_back(rand()%10);
}
template <class T>
void rmset(T &t, int l){
for(int i=0;i<l;i++)t.insert(rand()%10);
}
template <class T>
void rmap(T &t, int l){
for(int i=0;i<l;i++)t[i]=rand()%10;
}
template <class T>
void show(T& t) {
for (auto element : t)cout << element << " ";
cout << endl;
}
template <class T>
void showmap(T &t){
for(auto element:t)cout<<element.second<<" ";
cout<<endl;
}
int main() {
vector<int> v;
list<int> l;
multiset<int> s;
map<int,int> m;
int num = 30;
int rtd = rand() % 10;
rvec(v, num);
rlist(l, num);
rmset(s, num);
rmap(m, num);
show(v);
show(l);
show(s);
showmap(m);
cout << endl;
auto last = unique(v.begin(), v.end());
v.resize(distance(v.begin(), last));
l.unique();
//something for list
//something for map
show(v);
show(l);
show(s);
showmap(m);
return 0;
}

启动后我得到了

0 0 1 1 1 1 1 2 2 2 3 3 3 3 4 5 5 5 5 5 5 6 7 7 8 8 8 8 9 9用于设置和

地图2 9 2 0 7 2 6 0 8 5 5 1 9 0 3 1 9 3 0 5 3 0 9 3 1 7 2 2 0 7

c++ 在集合中获取唯一值

集合中的所有值都是唯一的,至少在比较函数方面是这样。

如果您需要另一个比较函数的唯一性f2,则将输入集中的元素复制到另一个使用f2的集合中。或者,将元素复制到向量中(任何顺序容器都可以,但数组很简单且通常很快(,然后排序并使用std::unique

上一段中描述的解决方案也适用于映射和多集:将元素复制到一个集合中,您就完成了。或者将它们复制到向量中,然后应用算法。