c++set集使用

#include<iostream>
#include<string>
#include<vector>
#include<set>
//set不能重複,multiple可以重複
using namespace std;

//寫一個函數用來描述set和muiltiset裏邊的數據
//把函數做成模板函數
template<typename Container>

void PrintContents(const Container &c);


int main()
{
	//set和multiple速度非常快
	//插入,刪除,查找速度很快
	set<int> a;
	multiset<int> ma;

	a.insert(60);
	a.insert(-1);
	a.insert(3);
	a.insert(30);
	a.insert(300);
	//a不允許重複

	cout << "顯示set裏邊的數據:" << endl;
	PrintContents(a);
	//set<int>::const_iterator i = a.begin();
	//while (i != a.end())
	//{
	//	cout << *i <<endl;
	//	++i;//插入之後會自動排序,set是一種紅黑樹
	//}

	ma.insert(60);
	ma.insert(a.begin(), a.end());
	ma.insert(3000);

	ma.count(3000);//計算ma有幾個3000
	
	cout << "multiset裏有幾個3000::" << ma.count(3000) << endl;

	//find查找和count
	set<int>::iterator  i=a.find(-1);//find的返回結果是一個迭代器
	if (i != a.end())
		cout << "找到了:" << *i << endl;
	else
		cout << "沒找到" << endl;

	//erase
	cout << "a裏有多少個數據" << a.size() << endl;

	cout << "刪除之前a裏的數據是:" << endl;
	PrintContents(a);
	int e = 0;
	cin >> e;
	a.erase(e);
	cout << "刪除之後的數據是:" << endl;
	PrintContents(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;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章