【C++标准库】特殊容器
特殊容器,又稱為容器適配器(Container Adapter),它們改造了標(biāo)準(zhǔn)STL容器,使之滿足特殊的要求。
Stack堆棧
使用stack時,需包含頭文件<stack>
- push() 將一個元素壓入棧內(nèi)
- pop() 從棧內(nèi)移除下一個元素,但是并不返回它
- top()? ? ? ? ?返回棧內(nèi)下一個元素,但并不移除它。
如果stack內(nèi)沒有元素,top()和pop()會導(dǎo)致不明確的行為,可采用size()或empty()來檢查容器是否為空。
Queue隊列
Queue實現(xiàn)出了一個FIFO先進(jìn)先出的結(jié)構(gòu),是一個典型的數(shù)據(jù)緩沖構(gòu)造。使用時需包含頭文件<queue>
- push() 將一個元素入隊列
- front()返回隊列中第一個元素,但不移除元素
- back()返回隊列中最后一個元素,但不移除元素
- pop()從隊列中移除一個元素,但不返回它
如果隊列內(nèi)沒有元素,front(),back()和pop()將導(dǎo)致不明確的行為,可采用size()或empty()來檢查容器是否為空。
Priority Queue優(yōu)先級隊列
priority queue內(nèi)的元素根據(jù)優(yōu)先級進(jìn)行了排序,使用時需包含頭文件<queue>
- push()將一個元素放入priority queue中
- top()返回priority queue中第一個元素,但并不移除
- pop()移除一個元素,但并不返回
如果優(yōu)先級隊列內(nèi)沒有元素,top()和pop()會導(dǎo)致不明確的行為,可采用size()或empty()來檢查容器是否為空。
#include <iostream> #include <queue> using namespace std;int main() {priority_queue<float> q;q.push(66.6);q.push(22.2);q.push(44.4);cout << q.top() << endl;q.pop();cout << q.top() << endl;q.pop();q.push(11.1);q.push(55.5);q.push(33.3);while (!q.empty()){cout << q.top() << endl;q.pop();}return 0; } View Code?BitSet
BitSet構(gòu)造出了一個內(nèi)含bit或Boolean值且大小固定的array,當(dāng)需要管理各式flag,并以flag任意組合來表現(xiàn)變量時,就可以運用bitset。
BitSet定義于頭文件<bitset>中
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference, 2nd Edition" * by Nicolai M. Josuttis, Addison-Wesley, 2012 * * (C) Copyright Nicolai M. Josuttis 2012. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <bitset> #include <iostream> using namespace std;int main() {// enumeration type for the bits// - each bit represents a colorenum Color {red, yellow, green, blue, white, black, //..., numColors};// create bitset for all bits/colorsbitset<numColors> usedColors;// set bits for two colorsusedColors.set(red);usedColors.set(blue);// print some bitset datacout << "bitfield of used colors: " << usedColors << endl;cout << "number of used colors: " << usedColors.count() << endl;cout << "bitfield of unused colors: " << ~usedColors << endl;// if any color is usedif (usedColors.any()) {// loop over all colorsfor (int c = 0; c < numColors; ++c) {// if the actual color is usedif (usedColors[(Color)c]) {//... }}} } View Code?
轉(zhuǎn)載于:https://www.cnblogs.com/larry-xia/p/9504007.html
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的【C++标准库】特殊容器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css中flex布局
- 下一篇: 一个只有十行的精简MVVM框架(下篇)