vector向量
向量(Vector)是一个封装了动态大小数组的顺序容器(Sequence Container)。跟任意其它类型容器一样,它能够存放各种类型的对象。可以简单的认为,向量是一个能够存放任意类型的动态数组。
1、头文件
#include<vector>//首先在程序开头处加上以包含所需要的类文件vector
using namespace std;//还有一定要加上
2、vector主要操作
vector<int> test1;
cout<< sizeof(test1)<<endl;//16
cout << test1.size() << endl;//0
vector<int> test3(5);
cout << sizeof(test3) << endl;//16
cout << test3.size() << endl;//5
test1.push_back(1);//动态数组,输入元素:1
test3.push_back(1);//元素:0 0 0 0 0 1
test1.pop_back();//无返回值,去掉最后一个元素
3、截取vector
vector<int>::const_iterator begin = num.begin();
vector<int>::const_iterator last = num.begin() + length;
vector<int> new_arr(begin, last);
stack栈
先进后出
1、头文件
#include <stack>
2、基本操作
stack<int> S;
cout << sizeof(S) << endl;//20
cout <<boolalpha<< S.empty() << endl;//栈S为空,返回true
S.push(3);//3
S.push(7);//3 7
S.push(1);//3 7 1
cout << S.size() << " ";//栈大小为3
cout << S.top() << " ";//输出栈顶元素:1
S.pop();//移除栈顶元素,剩余3 7
cout << S.top() << " ";//输出栈顶元素:7
S.pop();//移除栈顶元素,剩余3
cout << S.top() << " ";//输出栈顶元素:3
S.push(5);//3 5
cout << S.top() << " ";//输出栈顶元素:5
S.pop();//移除栈顶元素,剩余3
cout << S.top() << endl;//输出栈顶元素:3
cout << boolalpha << S.empty() << endl;//栈S不为空,返回false
S.emplace(2);
queue队列
先进先出
1、头文件
#include<queue>
2、基本操作
queue<int> Q;
cout << sizeof(Q) << endl;//20
cout << Q.size() << endl;//0
cout << boolalpha << Q.empty() << endl;//队列Q为空,返回true
Q.push(1);Q.push(2);Q.push(3);//队列:1 2 3
cout << Q.size() << endl;//3
cout << Q.front() << endl;//输出队首:1
Q.pop();//移除队首元素
cout << Q.front() << endl;//输出队首:2
输出栈中所有的元素
while (!Q.empty())
{
cout>>Q.front();
Q.pop();
}
map关联容器
1、头文件
#include<map>
2、基本操作
map<char, int> chineseNum;
chineseNum.insert(pair<char, int>('A', 0));
chineseNum['B'] = 1;
map<char, int>::iterator iter;
iter = chineseNum.find('C'); //iter 为 end
iter = chineseNum.find('A');//取出key为'A'的键值对,iter 为 ('A', 0)
cout << iter->first << '\t' << iter->second << endl;
int tmp = chineseNum['C'];//F不在map中,会将('F',0)添加进map,并返回0
cout << chineseNum.size() << endl;//3
if (chineseNum.find('C') != chineseNum.end())
cout << 'C';//C
//迭代器刪除
iter = chineseNum.find('C');
chineseNum.erase(iter);
//用關鍵字刪除
int n = chineseNum.erase('B');//如果刪除了會返回1,否則返回0
//用迭代器範圍刪除 : 把整個map清空
chineseNum.erase(chineseNum.begin(), chineseNum.end());
//等同於chineseNum.clear()
set集合容器
特点
set集合中不存在重复元素;
set集合中的元素都为有序排列,不管插入的顺序如何。
set不支持下标的操作
#include <set> //引用头文件
set<float> _set; //定义
_set.insert(1.0); //插入
_set.insert(2.0);
_set.insert(1.00);
_set.insert(0.00);
set<float>::iterator itr = _set.begin();
float f = *itr;
itr = _set.find(0);
f = *itr;
cout << *_set.rbegin(); //输出最后一个元素,默认最大
pair
pair <string,double> product1 ("tomatoes",3.25);
pair <string,double> product2;
pair <string,double> product3;
product2.first ="lightbulbs"; // type of first is string
product2.second =0.99; // type of second is double
product3 = make_pair ("shoes",20.0);