C++ STL学习——deque
程序员文章站
2022-12-10 16:07:17
在数据结构中还有一种很常见的队列叫做双端队列,我们在上一篇博客《C++ STL学习——queue》中讲到的队列queue是一种最标准的队列,只能在尾部插入数...
在数据结构中还有一种很常见的队列叫做双端队列,我们在上一篇博客《C++ STL学习——queue》中讲到的队列queue是一种最标准的队列,只能在尾部插入数据,在头部删除数据。而今天我们讲到的deque分别可以在两端进行插入与删除,可以说用起来更加的灵活。
(1)创建一个deque
deque deque1; deque deque2(deque1); deque deque3(10); deque deque4(10,0);
(2)deque尾部插入数据
deque1.push_back(1); deque1.push_back(2); deque1.push_back(3); deque1.push_back(4); PrintDeque(deque1);
(3)deque头部插入数据
deque1.push_front(5); deque1.push_front(6); PrintDeque(deque1);
(4)查看头部元素、尾部元素和某位置元素
cout << "头部元素为:" << deque1.front() << endl; cout << "尾部元素为:" << deque1.back() << endl; cout << "某位置的元素为:" << deque1.at(2) << endl; cout << "某位置的元素为:" << deque1[2] << endl;
(5)使用迭代器在某位置插入元素
// 使用迭代器插入或删除元素 deque::iterator iterInsert = deque1.begin(); iterInsert = iterInsert + 2; deque1.insert(iterInsert, 99); PrintDeque(deque1);
(6)使用迭代器在某位置删除元素
deque::iterator iterErase = deque1.begin(); iterErase = iterErase + 2; deque1.erase(iterErase); PrintDeque(deque1);
(7)size(), max_size()
cout << "deque1.size = " << deque1.size() << endl; cout << "deque1.max_size = " << deque1.max_size() << endl;
(8)头部、尾部删除元素
deque1.pop_back(); PrintDeque(deque1); deque1.pop_front(); PrintDeque(deque1);
(9)交换两个deque
// 交换两个deque deque dequeSwap; dequeSwap.push_back(11); dequeSwap.push_back(22); dequeSwap.push_back(33); cout << "deque1:" ; PrintDeque(deque1); cout << "dequeSwap:"; PrintDeque(dequeSwap); deque1.swap(dequeSwap); cout << "deque1:" ; PrintDeque(deque1); cout << "dequeSwap:"; PrintDeque(dequeSwap);
(10)判断deque是否为空
cout << "deque是否为空:" << deque1.empty() << endl; deque1.clear(); cout << "deque是否为空:" << deque1.empty() << endl; PrintDeque(deque1);
(11)迭代器打印deque
void PrintDeque(deque pDeque) { cout << "deque元素为:"; deque::iterator dequeIter; for (dequeIter = pDeque.begin(); dequeIter != pDeque.end(); dequeIter++) { cout << *dequeIter << " "; } cout << endl; }
上一篇: C语言零碎知识点
下一篇: 初识storm分布式流计算