C++primer第4版第九章顺序容器

来源:互联网 发布:分治算法的时间复杂度 编辑:程序博客网 时间:2024/05/17 22:15

Talk is cheap, show me the code.

  1. 容器的元素类型必须满足两个约束条件:

    元素类型必须支持赋值运算。
    元素类型对象必须可以复制。

  2. 所有引用类型没有实现赋值运算就不能作为容器元素类型。IO流类型不支持复制和赋值,所以不能作为容器元素类型。

  3. 当定义容器的容器时,注意一定要使用空格,以区分移位运算符:

    vector<vector<string> > lines;

  4. C++标准库的顺序容器为vector,list,deque,他们的迭代器全都支持自增和自减运算和等于和不等运算,但是只有vector和deque的迭代器支持加法减法运算和大于小于运算,list迭代器不支持加法减法运算和大于小于运算:

    list<int> list1 = {1, 2, 3};
    list<int>::iterator it = list1.end();
    it--;
    for (;it != list1.begin();it--) //实现list的逆序输出,注意不能使用list1.end()-1运算和大于小于运算
    cout << *it << endl;
    cout << *it << endl;

  5. 不要存储容器的end()迭代器,否则很容易导致该迭代器失效,比如:

    vector<int> vect = {1, 2};
    vector<int>::iterator first = vect.begin(), end = vect.end();
    while (first != last) //wrong, last每次循环都会失效,导致出错
    {
    first = vect.insert(++first, 42);
    first += 2;
    }

  6. 创建一个list

0 0
原创粉丝点击