vector
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> whq = {1, 2, 3};
cout << whq[1] << endl; // 2 支持随机访问
whq.push_back(4);
cout << whq.size() << endl; // 1 2 3 4 共4个
whq.pop_back();
cout << whq.size() << endl; // 1 2 3 共3个
cout << whq.empty() << endl; //false-> 0
whq.clear();
cout << whq.empty() << endl << endl; // true->1
// vector遍历
whq = {1, 2, 3};
for (int i = 0; i < whq.size(); i ++)
cout << whq[i] << endl; // 1 2 3
// 采用迭代器
for (vector<int>::iterator it = whq.begin(); it != whq.end(); it ++)
cout << *it << endl; // 1 2 3
cout << whq.front() << endl; // 1
cout << whq.back() << endl; // 3
return 0;
}
一维vector
// 3种等价写法:赋具体值
vector<int> a = {1, 2, 3};
vector<int> a({1, 2, 3});
vector<int> a{1, 2, 3};
// 定义shape与初始值
vector<int> a(10, 0);
定义二维vector, 如n*m的vector。
// n*m 的二维vector
vector<vector<int>> a(n, vector<int>(m));
// 初始化全0的vector:
vector<vector<int>> a(n, vector<int>(m, 0));
bool:
vector<vector<bool>> st(n, vector<bool>(m));
// 定义一些变量,,例如全局变量,但此时未知n等大小
vector<vector<bool>> st;
// ............................
// 赋值
st = vector<vector<bool>>(n, vector<bool>(n, false));
queue
#include <iostream>
#include <queue> // 包括queue与priority_queue
using namespace std;
int main(){
struct Rec{
int a, b, c;
bool operator> (const Rec& t) const {// 有sort则必须运算符重载,具体:小根堆重载>,大根堆重载<
return a > t.a;
}
};
queue<int> q;
q.push(1);
q.pop();
cout << q.front() << endl; // 0
cout << q.back() << endl; // 1
cout << " " << endl;
priority_queue<int> a; // 默认为大根堆
// 小根堆
priority_queue<int, vector<int>, greater<int>> b;
// 此处为结构体小根堆,需要手动重载>;若为大根堆则重载<
priority_queue<Rec, vector<Rec>, greater<Rec>> d;
d.push({3, 2}); // 3 < 100
d.push({100, 2});
cout << d.top().a << endl; // 3 查看堆顶元素
cout << d.top().b << endl; // 2
cout << d.top().c << endl; // 0 未赋值则默认为0
cout << d.empty() << endl; // false->0
cout << d.size() << endl; // 2
cout << " " << endl;
priority_queue<pair<int, int>> e;
e.push({10, 2});
e.push({3, 2});
cout << e.top().first << endl; // 10
return 0;
}
map
内部实现为红黑树
#include <iostream>
#include <map>
using namespace std;
int main(){
map<string, vector<int>> m;
// 两种方法
m.insert({"whq", vector<int>()});
m["whq"] = vector<int>({1, 2, 3, 4, 5});
cout << m["whq"][2] << endl; // 3
cout << (m.find("whq") == m.end()) << endl << endl; // false->0
return 0;
}
bitset
#include <iostream>
#include <bitset>
using namespace std;
int main(){
bitset<1000> bb;
bitset<1000> cc;
bitset<1000> dd;
bb[0] = 1;
bb[2] = 1; // bb.set(2); reset则设为0
cc[1] = 1;
cout << (bb | cc).count() << endl; // 3 返回1的个数为3
cout << bb[0] << " " << bb[1] << endl; // 1 0
cout << bb.count() << endl; // 2
cout << sizeof(bb) << endl; // 128
return 0;
}
pair
#include <iostream>
using namespace std;
int main(){
pair<int, string> a;
a = {2018, "whq"};
cout << a.first << " " << a.second << endl; // 2018 whq
a = make_pair(1, "hello");
cout << a.first << ' ' << a.second << endl; // 1 hello
return 0;
}