kong000dao0 2020-04-29
这个部分和 vector 几乎一样
第二 使用at 方法 如: dequeName.at(2) = 100; //小心越界
第三 接口返回的引用 dequeName.front() 和 deqIntA.back()
如下代码:
#include <iostream>
#include <deque>
using namespace std;
int main()
{
deque<int> deqInt_A;
deqInt_A.push_back(1);
deqInt_A.push_back(2);
deqInt_A.push_back(3);
cout << "deqInt_A 初始的元素:" << endl;
for (unsigned int i = 0; i < deqInt_A.size(); i++)
{
cout << deqInt_A[i] << endl;
}
deqInt_A.at(0) = 666;
deqInt_A[1] = 888;
cout << "用 .at 和下标操作符进行修改后 deqInt_A 中的元素:" << endl;
for (unsigned int i = 0; i < deqInt_A.size(); i++)
{
cout << deqInt_A[i] << endl;
}
return 0;
}打印结果:

也可以对普通变量进行赋值,如下代码:
#include <iostream>
#include <deque>
using namespace std;
int main()
{
deque<int> deqInt_A;
deqInt_A.push_back(1);
deqInt_A.push_back(2);
deqInt_A.push_back(3);
//可以给普通变量赋值,这种方式可行,但比较危险,因为参数超出会导致访问越界
cout << "使用不建议的方式读容器 deque 里的值" << endl;
int INT_1 = deqInt_A.at(0);
printf("INT_1 = %d\n", INT_1);
int INT_2 = deqInt_A[1];
printf("INT_2 = %d\n", INT_2);
//建议用frout() back()进行访问(包括上边的例子也是)
cout << "使用 frout() back() 的方式读容器 deque 里的值" << endl;
int INT_3 = deqInt_A.front(); //frout返回首元素的引用
printf("INT_3 = %d\n", INT_3);
int INT_4 = deqInt_A.back(); //back 返回尾元素的引用
printf("INT_4 = %d\n", INT_4);
//遍历容器
cout << "遍历容器:" << endl;
for (int i = 0; i < deqInt_A.size(); i++)
{
cout << deqInt_A[i] << endl;
}
//将值赋值回首位元素的引用
cout << "将收尾的值各加 1 用首位元素的引用赋值回去" << endl;
INT_3++;
INT_4++;
deqInt_A.front() = INT_3;
deqInt_A.back() = INT_4;
for (int i = 0; i < deqInt_A.size(); i++)
{
cout << deqInt_A[i] << endl;
}
return 0;
}打印结果:

deque.begin(); //返回容器中第一个元素的迭代器。
deque.end(); //返回容器中最后一个元素之后的迭代器。
deque.rbegin(); //返回容器中倒数第一个元素的迭代器。
deque.rend(); //返回容器中倒数最后一个元素之后的迭代器。
deque.cbegin(); //返回容器中第一个元素的常量迭代器。
deque.cend(); //返回容器中最后一个元素之后的常量迭代器。
看如下代码示例:
#include <iostream>
#include <deque>
using namespace std;
int main()
{
int test[] = { 111,222,333,444 };
deque<int> deqInt_A(test, test + 4);
//deque.begin()
cout << "使用迭代器 begin() 遍历容器" << endl;
deque<int>::iterator it_begin = deqInt_A.begin(); //获得容器中第一个元素的地址
for (; it_begin != deqInt_A.end(); it_begin++)
{
(*it_begin)++; //普通的 begin() 迭代器读到的值是可以修改的
cout << *it_begin <<" ";
}
//deque.rbegin()
cout << "\n\n使用迭代器 rbegin() 遍历容器" << endl;
deque<int>::reverse_iterator it_rbegin = deqInt_A.rbegin(); //注意迭代器类型是 reverse_iterator,deqInt_A.rbegin()返回的是末尾地址
for (; it_rbegin!=deqInt_A.rend(); it_rbegin++) //reverse_iterator类型++ 是像首地址移动,deqInt_A.rend()返回的是首地址
{
(*it_rbegin)--; // rbegin() 迭代器读到的值是可以修改的
cout << *it_rbegin << " ";
}
//deque.cbegin()
cout << "\n\n使用迭代器 cbegin() 遍历容器" << endl;
deque<int>::const_iterator it_cbegin = deqInt_A.cbegin(); //注意迭代器类型是 const_iterator
for (; it_cbegin!=deqInt_A.cend(); it_cbegin++)
{
//(*it_begin)++; //因为是 cbegin() 读取到的内容不能修改
cout << *it_cbegin << " ";
}
return 0;
}打印内容:

============================================================================================================================