C++ 在集合和映射容器中获取唯一值
c++ get unique values in set and map containers
如何在容器中获取唯一值? 我看到矢量和列表有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
。
上一段中描述的解决方案也适用于映射和多集:将元素复制到一个集合中,您就完成了。或者将它们复制到向量中,然后应用算法。
相关文章:
- C++ 在集合和映射容器中获取唯一值
- 获取模板函数/泛型 lambda 的唯一返回类型
- 获取窗口监视器的唯一标识符
- 从 Android 上的 c++ 获取唯一的设备标识符
- 在文本中的两个非唯一字符串之间获取子弦
- 从eigen3矩阵中获取唯一的值
- 如何从长度为 n 的字符串中获取 lengh k 的所有唯一排列的数量
- 如何从向量中获取随机和唯一值?
- 获取C++中的随机唯一整数
- 从数组中获取唯一编号,完全删除重复项
- 如何从基类的唯一指针获取子类的成员
- C++:通过进程id、进程句柄和标题名称从进程中获取唯一窗口的窗口句柄的最佳方法
- 获取系统的唯一标识符(而不是MAC地址)
- 获取在同一查询中创建的行的唯一 ID
- 如何获取唯一指针列表
- 连续获取 2 个唯一数字
- 如何获取计算机的唯一标识符
- 从容器中获取唯一元素[c++]
- 获取唯一编号并知道它们何时被释放
- IOKit 并获取唯一 ID