标签:
set, multiset, map, multimap
multiset
template<class Key, class Pred = less<Key>>, class A=allocator<Key> >
class multiset { …. };
template<class T>
struct less : public binary_function<T, T,bool>
{bool operator()(const T&x , const T&y){ return x<y ;} const; };
//less模板是靠 < 来比较大小的。
set
template <class Key , class Pred = less<Key>, class A = allocator<Key> >
class set{ … }
插入set中已有的元素时,忽略插入。
multiset实验代码:
#include <iostream> #include <set> using namespace std; template <class T> void Print(T first, T last) { for (; first != last; first++) { cout << *(first) << " "; } cout << endl; } 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 &a) { o << a.n; return o; } friend class Myclass; }; struct Myclass { bool operator()(const A & a1, const A & a2) { return (a1.n % 10 < a2.n % 10); } }; typedef multiset<A> Mset1; typedef multiset<A, Myclass> Mset2;//重新定义排序 int main() { const int size = 6; A a[size] = { 1, 12, 9, 20, 89 ,78}; Mset1 m1; m1.insert(a, a + size); Print(m1.begin(), m1.end()); m1.insert(20); cout << "inserted the number:20" << endl; Print(m1.begin(),m1.end()); Mset1::iterator it; it = m1.find(20); m1.erase(it); cout << "deleted the number:20" << endl; Print(m1.begin(), m1.end()); Mset2 m2; m2.insert(m1.begin(), m1.end()); cout << "the multiset m2 is :" << endl; Print(m2.begin(), m2.end()); return 0; }
运行结果:
set实验代码:
#include <iostream> #include <set> using namespace std; int main() { typedef set<int>::iterator IT; int a[5] = { 3,4,6,1,2 }; set<int> st(a,a+5); // st里是 1 2 3 4 6 pair< IT,bool> result; result = st.insert(5); // st变成 1 2 3 4 5 6 if( result.second ) //插入成功则输出被插入元素 cout << * result.first << " inserted" << endl; //输出: 5 inserted if( st.insert(5).second ) cout << * result.first << endl; else cout << * result.first << " already exists" << endl; //输出 5 already exists pair<IT,IT> bounds = st.equal_range(4); cout << * bounds.first << "," << * bounds.second ; //输出:4,5 return 0; }
参考链接:
https://www.coursera.org/learn/cpp-chengxu-sheji
标签:
原文地址:http://www.cnblogs.com/helloforworld/p/5655444.html