9.2 Container Library Overview(容器库概述)

9.2.1迭代器

1.迭代算术操作只适用于string, vector, dequearray,其他的容器类型都不行。

 

2.在容器中的元素从begin(first)开始到end(last)结束(不包括end)。

 

3.

list<string>::iterator it5 = a.begin();
list<string>::const_iterator it6 = a.begin();

auto it7 = a.begin()//if a is const, it7 is const_iterator
auto it8 = a.begin()//it8 is const_iterator

 

 

4.当对容器不需要访问时,使用cbegin() 和 cend()。

 

5.伴随大小的构造只对顺序容器有效,对关联容器无效。

vector<int> vec(10, 5)//10个5

 

6.赋值相关的操作符对容器都起作用,赋值操作符将有右操作对象的元素赋值到左操作的全部元素对象。

 

7.在assign被调用时,迭代器调用不需要涉及到容器。使用assign后,对原来元素的指针,引用,迭代器都会失效。

 

8.对于container在swap后,指针,引用,迭代器依然绑定在相同的元素上 ,array在swap后,改变。

#include <bits/stdc++.h>

using namespace std;

int main()
{
    vector<int> vec = { 8, 4 , 5 };
    vector<int> vec1 = {6, 1 , 5, 9 };

    auto it = vec.begin();

    cout << *it << endl;//8

    vec.swap(vec1);

    cout << *it << endl;//8

    system("PAUSE");
    return 0;
}

 

#include <bits/stdc++.h>
#include <array>
using namespace std;

int main()
{
    array<int, 10> arr = { 1, 2, 3 };
    array<int, 10> arr1 = { 8, 5 };

    auto it = arr.begin();

    cout << *it << endl;//1

    swap(arr, arr1);
    //arr.swap(arr1);

    cout << *it << endl;//8

    system("PAUSE");
    return 0;
}

 

#include <bits/stdc++.h>

using namespace std;

int main()
{
    vector<int>::difference_type count;
    //deffirence_type为signed表示迭代器之间的距离iter1 - iter2
    system("PAUSE");
    return 0;
}

 

#include <bits/stdc++.h>

using namespace std;

int main()
{
    vector<string> vec = { "ni", "hao", "a!" };
    
    cout << *vec.rbegin() << endl;//"!a"
    //rbegin()为::reverse_iterator,反向迭代器
    system("PAUSE");
    return 0;
}

 

#include <bits/stdc++.h>
#include <array>

using namespace std;

int main()
{
    list<int> li = { 1, 2, 3, 4 };

    auto it = li.cbegin();

    cout << *it << endl;

    li.assign(10, 5);
    //错误:cout << *it << endl;
    cout << *li.cbegin() << endl;
    
    system("PAUSE");
    return 0;
}
posted @ 2018-10-23 21:39  Hk_Mayfly  阅读(203)  评论(0)    收藏  举报