复习一下c++的基础知识
字符串string
构造函数
1 2 3 4
| string str; string str(str1); string str("hello"); string str(len,'a');
|
常用函数
1 2 3 4 5 6 7 8 9 10 11 12
| str.assign("abc"); str.assign("abc",2); str.assign("a",5); str.length(); str.resize(len,'a'); str.swap(str1); str.append("ABC"); str.find('a'); string newstr = str.substr(start,length); std::stoi(str) std::to_string(value) str.c_str()
|
accumulate函数
需要#include <numeric>
1 2
| int sum = accumulate(vec.begin() , vec.end() , origin);
|
reverse函数
需要#include<algorithm>
1 2
| reverse(str.begin(),str.end()); reverse(vec.begin(),vec.end());
|
sort函数
需要#include<algorithm>
1
| sort(first_pointer, first_pointer+n, cmp)
|
sort()
默认为升序排列,如果要改变顺序或者适应结构体需要cmp函数
1 2 3 4 5 6 7
| bool compare(int a,int b){ return a<b;
}
sort(vec.begin(), vec.end(), compare)
|
set
需要#include<set>
1 2 3 4 5 6 7 8 9
| s.begin(); s.end() s.clear(); s.empty(); s.insert(); s.erase(); s.size(); s.count(value); s.find(value);
|
以下部分参考知乎专栏
vector
需要#include<vector>
1 2 3 4 5 6 7 8 9
| vector<int>vec; vec.clear(); vec.push_back(1); vec.pop_back(); vec.pop_front(); vec.end() vec[0]; vec.insert(pos,value) vec.size();
|
map
需要#include<map>
1 2 3 4 5 6 7
| map<char,int>char2int; char2int.clear(); char2int['a'] = 2; char2int.count['a']; char2int.erase('a'); char2int.size(); char2int.find('a')
|
queue
需要#include<queue>
1 2 3 4 5 6 7
| queue<int>que; que.empty(); while(!que.empty())que.pop(); que.push(1); que.pop(); que.front(); que.size();
|
stack
需要#include<stack>
1 2 3 4 5 6
| stack<int>st; st.empty(); st.push(); st.pop(); st.top(); st.size();
|
lower_bound与upper_bound
需要#include<algorithm>
,同时数组要求有序。
1 2
| lower_bound(begin,end,value) upper_bound(begin,end,value)
|
二者的区间都是左闭右开(配合stl类型中的begin()与end())。需要得到下标位置可以减去头指针。
stl容器遍历的迭代写法
1 2 3 4 5 6 7 8
| for(vector<int>::iterator iter=vec.begin();iter!=vec.end();iter++){ cout<<*iter<<endl; }
for(vector<int>::reverse_iterator iter=vec.rbegin();iter!=vec.rend();iter++){ cout<<*iter<<endl; }
|
链表与数组
数组初始分配连续空间,可以下标访问(随机访问),但是修改麻烦。适合访问多修改少的情况。
链表使用指针链接,不能下标访问,插入删除方便。适合修改多访问少的情况。