C++ Primer 读书笔记 第十章

1. map和set中的key是唯一的,multimap和multiset中的key可以出现多次。

2. Whenever we use an associative container, its keys have not only a type, but also an associated comparsion function.

3. The value_type is a pair and that we can chagne the value but not the key member of that pair.

4. 用下标插入元素时,内部操作是这样的:

    - 找key,找不到

    - 把key-value pair 插入到map中,其中value是其默认初始化值

    - 然后再取出key对应的元素,对value进行赋值

5. 用insert函数进行插入元素操作,如果key已存在,则对应的元素保持不变

    insert函数有一个返回值,是一个pair,构造如下,可通过bool值来判断是否插入了。

pair<map<string, int>::iterator, bool> ret = word_count.insert(make_pair(word, 1));
if (!ret.second)
    ++ret.first->second;

6. 不要用下标操作来查找一个元素,一旦这个key不存在的话,它会创建一个key,对应的value为默认初始值。

    用find函数,find函数会返回一个指针,用这个指针对元素进行操作

7. map中的erase函数,当key存在时,就删除,返回1,不存在,不做任何事,返回0.

#include <iostream>
#include <map>
#include <string>
#include <utility>
using namespace std;

class A
{
private:
    int age;
public:
    A() : age(0) { }
    A (int a) 
{ age
= a; } int get_age() const { return age; } bool operator < (const A &a) const { return (age < a.age); } }; int main() { map<string, int> m; m.insert(make_pair("abc", 1)); m.insert(make_pair("abc", 4));//do nothing cout << m["abc"] << endl; cout << m.size() << endl; cout << m.count("abc") << endl; A a = A(5); cout << a.get_age() << endl; A a1(6); A a2(1); A a3(2); A a4(10); A a5(5); map<A, int> mapa; mapa.insert(make_pair(a1, 1)); mapa.insert(make_pair(a2, 2)); mapa.insert(make_pair(a3, 3)); mapa.insert(make_pair(a4, 4)); mapa.insert(make_pair(a5, 5)); for (map<A, int>::iterator it = mapa.begin(); it != mapa.end(); ++it) { cout << "A.age: " << (it->first).get_age() << "\t"; cout << "value: " << it->second << endl; } return 0; }

8. Just as we cannot change the key part of a map element, the keys in a set are also const.

9. set, multimap, multiset都没有下标操作

10. map.lower_bound(k)

      map.upper_bound(k)

      m.equal_range(k) -> return a pair of iterators. first is equivalent to lower_bound(), second is equivalent to upper_bound()

原文地址:https://www.cnblogs.com/null00/p/3102912.html