image.png

预备知识:pair模板

  1. template <class _T1, class _T2>
  2. struct pair {
  3. typedef _T1 first_type;
  4. typedef _T2 second_type;
  5. _T1 first;
  6. _T2 second;
  7. pair():first(), second(){}
  8. pair(const _T1 & __a, const _T2 & __b) : first(__a), second(__b){}
  9. template<class _U1, class _U2>
  10. pair(const pair<_U1, class _U2> & __p): first(__p.first), second(__p.second){}
  11. };
  12. // map/multimap容器里面放的都是pair模板类的对象,且按照first从小到大排序
  13. // 第三个构造函数用法示例:
  14. pair<int, int> p(pair<double, double> (5.5, 4.6));
  15. // p.first = 5, p.second = 4.6

multiset

image.png

multiset成员函数

image.png
image.png

用法示例

/*

  • 正确示例 ```cpp

    include

    include

    using namespace std; template void Print(T first, T last) { for(; first != last; ++first)
    1. cout << *first << " ";
    cout << endl; } class A { private:
    1. 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) {
    1. o << a.n;
    2. return o;
    } friend class MyLess; };

strcut MyLess { bool operator()(const A & a1, const A & a2) {return (a1.n & 10 < (a2.n % 10);}
};

typedef multiset MSET1; // 用”<”比较大小 typedef multiset MSET2; // 用MyLess比较大小

void main() { const int SIZE = 6; A a[SIZE] = {4, 22, 19, 8, 33, 40}; MSET1 m1; m1.insert(a, a + SIZE); m1.insert(22); cout << m1.count(22) << endl; // 输出 2 Print(m1.begin(), m1.end()); // 输出 4 8 19 22 22 33 40 // m1元素:4 8 19 22 22 33 40 MSET1:iterator pp = m1.find(19); if(pp != m1.end()) // 条件为真说明找到了 cout << “found” << endl; // 输出 found // 输出 22,33 cout << m1.lower_bound(22) << “,” << m2.upper_bound(22) << endl; // pp指向被删除元素的下一个元素 pp = m1.erase(m1.lower_bound(22), m1.upper_bound(22)); Print(m1.begin(), m1.end()); // 输出 4 8 19 33 40 cout << *pp << endl; // 输出 33

  1. MSET2 m2; // m2中的元素按照个位大小从小到大排序
  2. m2.insert(a, a+SIZE);
  3. Print(m2.begin(), m2.end()); // 输出 40 22 33 4 8 19

}

  1. <a name="QS5gt"></a>
  2. # set
  3. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/805730/1589444256099-e4bf603e-ba52-416c-b331-fbb547318445.png#align=left&display=inline&height=207&margin=%5Bobject%20Object%5D&name=image.png&originHeight=413&originWidth=1165&size=61056&status=done&style=none&width=582.5)
  4. - 重复的意思是 "a < b" 和 "b < a"都不成立
  5. ```cpp
  6. #include <iostream>
  7. #include <set>
  8. using namespace std;
  9. void main() {
  10. typedef set<int>::iterator IT;
  11. int a[5] = {3,4,6,1,2};
  12. set<int> st(a, a+5); // 这里是 1 2 3 4 6
  13. pair<IT, bool> result;
  14. result = st.insert(5); // st变成 1 2 3 4 5 6
  15. if(result.second)
  16. cout << *result.first << "inserted" << endl; // 输出:5 inserted
  17. if(st.insert(5).second)
  18. cout << *result.first << endl;
  19. else
  20. cout << *result.first << " already exists" << endl; // 输出 5 already exists
  21. pair<IT, IT> bounds = st.equal_range(4);
  22. cout << *bound.first << "," << *bounds.second; // 输出: 4,5
  23. }