C++中multiset和set容器及用法

C++中set和multiset都是關聯容器,與順序容器的差別在於,關聯容器中的元素都是按照某一排序規則,有序排列的。而set與multiset的區別在於,插入set中已有元素時,忽略插入

1.0 multiset類模板

template<class Key,class Pred=less<Key>,class A=allocator<Key> >
class multiset{...};

其中參數Pred可以是函數指針或者函數對象,Pred決定了“一個比另一個小”的規則。缺省情況下規則爲less< Key >。less模板的定義如下:

tempalte<class T>
struct less:public binary_function<T,T,bool>
{bool operator()(const T&x,const T&y){return x<y;} const;};

缺省規則是普通意義上的大小比較原則,但是也可以自己定義比較的規則,比如按照個位數大小關係決定大小。

2.0 multiset成員函數

在這裏插入圖片描述

3.0 實例

  • 利用函數對象重定義比大小規則,按照個位數大小比較
//**函數對象類定義
class A {
private:
	int n;
public:
	A(int n_):n(n_){}
	friend bool operator<(const A&a1, const A&a2) { return a1.n < a2.n; }
	friend ostream&operator<<(ostream&o, const A&a3) { o << a3.n; return o; }
	friend class Myless;
};

//**圓括號重載,定義比大小規則
struct Myless
{
	bool operator()(const A&a1,const A&a2)
	{
		return (a1.n % 10) < (a2.n % 10);	//按個位數比大小
	}
};
  • 分別按照默認和新規則建立的關聯容器
typedef multiset<A> MSET1;		//默認less<Key>比大小函數的關聯容器
typedef multiset<A, Myless> MSET2;		//以Myless定義的比大小函數的關聯容器
  • 成員函數實例(count(),find(),lower_bound,upper_bound(),erase()
int main()
{
	const int SIZE = 6;
	A a[SIZE] = { 4,22,19,8,33,40 };
	MSET1 m1;		//m1中元素按照從小到大排列
	m1.insert(a, a + SIZE);
	m1.insert(22);

	//**count函數
	cout << "1)" << m1.count(22) << endl;
	cout << "2)";Print_interval(m1.begin(), m1.end());		//4 8 19 22 22 33 40

	//**find函數
	MSET1::iterator pp = m1.find(19);
	if (pp != m1.end())
		cout << "Found" << endl;

	//**lower_bound:找最大位置it,使得[begin(),it)中所有元素小於指定值
	//**upper_bound:找最小位置it,使得(it,end()]中所有元素大於指定值
	cout << "3)";cout << *m1.lower_bound(22) << "," << *m1.upper_bound(22) << endl;	//22 33

	//**erase函數,返回迭代器爲刪除元素後一個元素位置
	pp = m1.erase(m1.lower_bound(22), m1.upper_bound(22)); //刪22 22,erase也是左閉右開,因此不包括33
	cout << "4)";Print_interval(m1.begin(), m1.end());		//4 8 19 33 40
	cout << "5)";cout << *pp << endl;		//33

	MSET2 m2;		//m2中元素按照個位數從小到大排列
	m2.insert(a, a + SIZE);
	cout << "6)";Print_interval(m2.begin(), m2.end());		//40 22 33 4 8 9
	return 0;
}

需要注意的是,erase()函數當刪除某一區間時,所包含的區間也是左閉右開的區間。即區間最後一個元素不刪除!

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