vector
//①通过迭代器访问:
vector<int> v;
vector<int>::iterator it;
for (it = v.begin(); it != v.end(); it++) {
cout << *it;
}
//②访问第i个
v[i] == *(v.begin() + i)
//③删除尾元素
v.pop_back();
//④在任意迭代器it处插入一个元素
v.insert(v.begin() + 2; -1); //将-1插入v[2]的位置
//⑤删除元素
v.erase(v.begin() + 3);
v.erase(v.begin() + 1, v.begin() + 4); //删除[1, 4)
set
//①set定义
set<int> st; //集合, 内部自动有序且不含重复元素
//②set访问只能通过迭代器
set<int>::iterator it;
for (it = st.begin(); it != st.end(); it++) {
cout << *it;
}
//③插入
st.insert(1);
//④查找
set<int>::iterator it = st.find(2);
cout << *it; //cout << *st.find(2);
//⑤删除
st.erase(st.find(100));
st.erase(st.find(100), st.end()); //删除[first, end)
string
//①插入
str.insert(3, str2);
str.insert(str.begin() + 3, str2.begin(), str2.end());
//②删除
str.erase(str.begin() + 4);
str.erase(str.begin() + 2, str.end() - 1);
//③查找
int pos = str.find(str2, 8); //从str[8]开始查找, 返回其第一次出现的位置
if (pos != -1)
cout << pos << endl;
if (pos != string::npos)
cout << pos << endl;
if (pos != str.npos)
cout << pos << endl;
//④替换
str.replace(10, 4, str2); //str[10]开始的4个
str.replace(str.begin(), str.begin() + 5, str2);
map
//①访问
map<char, int> mp;
mp['c'] = 20; //覆盖, 没有则新建映射
map<char, int>::iterator it;
for (it = mp.begin(); it != mp.end(); it++) {
cout << it -> first << it -> second;
}
//②查找
map<char, int>::iterator it = mp.find('b'); //失败返回mp.end()
//③删除
mp.erase(mp.find('b'));
mp.erase('b');
mp.erase(mp.find('b'), mp.end());
priority_queue
//①定义:优先队列, 队首元素是优先级最高的
//②使用
priority_queue<int> pq;
pq.push(2);
pq.top();
pq.pop();
if (pq.empty())
int len = pq.size();
//③优先级设置
priority_queue<int, vector<int>, greater<int>> q; //优先级最小的放在队首
struct fruit {
string name;
int price;
bool operator < (fruit f2) {
return price < f2.price; //价格高的优先级高, 与sort相反
}
};
pair
//①定义
pair<string, int> p("hh", 5);
//②临时定义
pair<string, int>("hh", 5);
make_pair("hh", 5);
//访问
cout << p.first << " " << p.second;
algorithm
//①有序容器,选择[first, last)范围内第一个值大于等于val的元素
int *lowerPos = lower_bound(a, a + 10, 3);
//②有序容器,选择[first, last)范围内第一个值大于val的元素
int *upperPos = upper_bound(a, a + 10, 3);
//③val在容器中的位置为[lowerPos - a, upperPos - a]
cout << lowerPos - a << " " << upperPos - a;
参考
《算法笔记》(胡凡)