STL multiset使用說明與代碼演示

       STL multiset特點
       (1)數據有序,可重複
       (2)刪除元素時,相同的所有元素都會被刪掉

       使用時需要包含頭文件<set>.

       代碼:

#include <iostream>
#include <set>

using namespace std;

//輸出multiset
void out(const multiset<int> obj)
{
	for (auto item : obj)
	{
		cout << item << " ";
	}
	cout << endl;
}

int main()
{
	//創建multiset對象
	multiset<int> ms = { 1,2,6,2,4,3,3,8 };

	out(ms);

	//刪除操作
	ms.erase(2);
	
	out(ms);

	//查找是否包含元素4
	auto it4 = ms.find(4);
	if (it4 != ms.end())
	{
		cout << "包含元素4" << endl;
	}
	else
	{
		cout << "沒有找到" << endl;
	}

	ms.insert(9);
	ms.insert(9);
	ms.insert(9);

	out(ms);

	//查找並輸出多個元素
	//pair<multiset<int>::iterator, multiset<int>::iterator> pa = ms.equal_range(9);
	//返回值太長,用auto關鍵字自動推導
	auto pa = ms.equal_range(9);
	for (auto it = pa.first; it!=pa.second; it++)
	{
		cout << *it << " ";
	}
	cout << endl;

	return 0;
}

  運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章