# include<iostream>
# include<deque>
# include<algorithm>//标准算法的头文件
using namespace std;
void printDeque(const deque<int>& d)
{
for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)//容器中的数据为只读
{
cout << *it << " ";
}
cout << endl;
}
//构造,赋值操作
void test01()
{
deque<int>d1;
for (int i = 0; i <= 10; i++)
{
d1.push_back(i);
}
printDeque(d1);
deque<int>d2(d1.begin(), d1.end());
printDeque(d2);
deque<int>d3(10, 100);
printDeque(d3);
deque<int>d4(d3);
printDeque(d4);
}
void test02()
{
deque<int>d2;
for (int i = 0; i < 10; i++)
{
d2.push_back(i);
}
printDeque(d2);
deque<int>d1;
d1 = d2;
printDeque(d1);
deque<int>d3;
d3.assign(d1.begin(), d1.end());
printDeque(d3);
deque<int>d4;
d4.assign(10, 100);
printDeque(d4);
}
//deque大小操作
//deque没有容量
void test03()
{
deque<int>d1;
for (int i = 0; i < 10; i++)
{
d1.push_back(i);
}
printDeque(d1);
if (d1.empty())
{
cout << "d1为空" << endl;
}
else
{
cout << "d1不为空"<<endl;
cout << d1.size() << endl;//没有容量这一概念
}
d1.resize(5,1);
printDeque(d1);
d1.pop_back();
printDeque(d1);
d1.pop_front();
printDeque(d1);
//
}
//deque的插入和删除操作
void test04()
{
//两端操作
deque<int>d1;
d1.push_back(10);
d1.push_back(20);
d1.push_front(100);
d1.push_front(200);
printDeque(d1);
d1.pop_back();
d1.pop_front();
printDeque(d1);
d1.insert(d1.begin(), 1000);
d1.insert(d1.begin(), 10000);
printDeque(d1);
//按照区间进行插入
deque<int>d2;
d2.push_back(1);
d2.push_back(2);
d2.push_back(3);
d1.insert(d1.begin(), d2.begin(), d2.end());
printDeque(d1);
//删除
deque<int>::iterator it = d1.begin();
it++;
d1.erase(it);
printDeque(d1);
//按照区间操作进行删除
d1.erase(d1.begin(), d1.end());
printDeque(d1);
}
//deque容器的数据存取操作
void test05()
{
deque<int>d;
for (int i = 0; i <= 10; i++)
{
d.push_back(i);
}
for (int i = 0; i < d.size(); i++)
{
cout << d[i] << " ";
}
cout << endl;
//通过at方式访问元素
for (int i = 0; i < d.size(); i++)
{
cout << d.at(i) << " ";
}
cout << endl;
cout << d.front() << endl;
cout << d.back() << endl;
}
void test06()
{
deque<int>d;
d.push_back(30);
d.push_back(20);
d.push_back(10);
d.push_back(200);
d.push_back(100);
d.push_back(400);
d.push_back(300);
printDeque(d);
//排序
sort(d.begin(), d.end());
//排序后的结果
printDeque(d);//从小到大进行升序
//对于支持随机访问的迭代器容器,都可以直接利用sort算法进行排序
}
int main(void)
{
test01();
cout << endl;
test02();
cout << endl;
test03();
cout << endl;
test04();
cout << endl;
test05();
cout << endl;
test06();
cout << endl;
return 0;
}
deque容器(复习用)
最新推荐文章于 2024-09-09 12:31:15 发布