C++ c++;在集合和映射容器中获取唯一值
如何在容器中获取唯一值? 我看到vector和list有C++ c++;在集合和映射容器中获取唯一值,c++,C++,如何在容器中获取唯一值? 我看到vector和list有unique(),但我找不到set和map有任何相似之处 UPD:我使用它在容器中生成值 #include <iostream> #include <vector> #include <list> #include <set> #include <map> using namespace std; template <class T> void rvec(T&
unique()
,但我找不到set和map有任何相似之处
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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
模板
无效rvec(T&T,内部l){
对于(int i=0;i
集合中的所有值都是唯一的,至少在比较函数方面是唯一的
如果需要另一个比较函数f2
的唯一性,则将输入集中的元素复制到另一个使用f2
的集合中。或者,将元素复制到向量中(任何顺序容器都可以,但数组简单且通常快速),然后排序并使用std::unique
上一段中描述的解决方案也适用于map和multiset:将元素复制到一个集合中,您就完成了。或者将它们复制到一个向量中,然后应用算法。std::set
中的值自动唯一。std::map
中的键也是如此。然后显示代码…@Mbroo值是随机的或不是无关的。请共享您关心的代码。请创建一个。您如何调用这些函数?如何打印得到的结果?这还不够。显示如何调用这些函数以及传递的参数