c++标准模板库(STL)我不会的地方总结

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;

参考

《算法笔记》(胡凡)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值