set(集) multiset(多集)
两者都是为了保存大量数据的,但是不同的是 前者 保存的数据不重复,而后者 是允许 重复的。
其保存的数据非常快,尤其是大量数据的时候。
但其有一个缺点:就是数据插入的时候比顺序容器慢些(vector 、 list 、 deque)。
基本操作有:
inset;
count 和 find;
erase
注意:不能通过find进行修改了。
两者可以进行自动排序哦!
#include <iostream>
#include <set>
using namespace std;
template<typename Container>
void PrintContents(const Container & c);
int main()
{
set<int> a;
multiset<int> multiset_a;
// a里面的数据不允许重复,但当你插入一个重复的数值的时候,它也不会报错,它会自动过滤
a.insert(3);
a.insert(6);
a.insert(1);
a.insert(100);
a.insert(100);
cout << "显示set里面的数据:" << endl; // set里面自动排序
/*set<int>::const_iterator i = a.begin();
while (i != a.end())
{
cout << *i << endl;
i++;
}
cout << endl;*/
PrintContents(a);
cout << a.count(300)<<endl;
// multiset_a就可以保存重复的数据
multiset_a.insert(a.begin(), a.end()); // a里面的数据全部插入multiset_a中
multiset_a.insert(100);
multiset_a.count(100);
// count(50) 集合里存在50这个元素有多少个
cout << "multiset_a里面有" << multiset_a.count(100) << "个3000" << endl;
//
cout << "显示multiset里面的数据:" << endl; // set里面自动排序
/*multiset<int>::const_iterator j = multiset_a.begin();
while (j != multiset_a.end())
{
cout << *j << endl;
j++;
}
cout << endl;*/
PrintContents(multiset_a);
//
system("pause");
return 0;
}
template<typename Container>
void PrintContents(const Container & c)
{
Container::const_iterator i = c.begin();
while (i != c.end())
{
cout << *i << endl;
++i;
}
cout << endl;
}
#include<iostream>
#include<set>
using namespace std;
typedef set<int> SETINT;
int main()
{
SETINT a;
a.insert(5);
a.insert(3);
a.insert(1);
a.insert(10);
SETINT::const_iterator i;
for (i = a.begin(); i != a.end(); i++)
{
cout << *i << endl;
}
SETINT::iterator i_found = a.find(3); // find返回的结果是一个迭代器
if (i_found != a.end())
{
cout << "找到了:" << *i_found << endl;
}
else
cout << "没有找到:" << endl;
// set 里面的数据不能直接修改,因为它默认会排序的。要想修改的话,先删除,之后重新添加
//
system("pause");
return 0;
}
#include<iostream>
#include<set>
using namespace std;
typedef multiset<int> MSETINT;
int main()
{
MSETINT a;
a.insert(43);
a.insert(78);
a.insert(22);
a.insert(-1);
a.insert(124);
a.insert(78);
MSETINT::const_iterator i;
cout << "multiset里面有" <<a.size() <<"个数据。"<< endl;
cout << "每一个数据是:" << endl;
for (i = a.cbegin(); i != a.end(); i++)
{
cout << *i << endl;
}
cout << "要删除的数据是:" << endl;
int nNumberToErase = 0;
cin >> nNumberToErase;
a.erase(nNumberToErase);
cout << "删除后:" << endl;
cout << "multiset里面有" << a.size() << "个数据。" << endl;
for (i = a.begin(); i != a.end(); i++)
{
cout << *i << endl;
}
a.clear();//清空
//
system("pause");
return 0;
}