STL
using namespace std;
vector
vector<int> v;
vector<int> v(nSize);
vector<int> v(nSize, t);
vector<int> v{1,2,3};
v.push_back(elem);
v.popback();
v.insert(pos,elem);
v.emplace_back(elem);
v.size();
v.erase(beg,end);
deque/list
deque is implemented by array, and lisi by double linked list. They can be used in the same way.
deque<int> dq(nSize, t);
list<int> lst(nSize, t);
dq.push_front(elem);
dq.pop_front();
dq.front();
dq.back();
dp.empty();
stack/queue
Here we list all member functions.
stack<int> s(nSize, t);
queue<int, list<int>> q(nSize, t);
s.empty(); s.emplace(); s1.swap(s2); s.push(elem); s.pop();
s.top();
q.front(); q.back();
priority_queue
ATTENTION: compare function less() corresponds to a max heap, and function greater() to a min heap.
priorty_queue<int> q;
priorty_queue<int, vector<int>, less<int>> q;
pair
pair <string, string> pair1("key1","value1");
pair <string, string> pair2(make_pair("key2","value2"));
pair1.first="key3";
pair1.second="value3";
map/multimap
map<string, int> mp;
map<string, int, greater<string>> mp2;
map<string, int> mmp;
mp.emplace("one",1);
mp["two"]=2;
mp.find("one");
int count = mmp.count("key");
int val = mp["two"];
mp.empty();
int count = mmp.erase("two");
mp.erase(mp.begin(), mp.end());
set/multiset
set<string> st;
multiset<string, less<string>> mst;
set.emplace("one");
set.find("one");
set.empty();
int count = mst.count("one");
int count = mst.erase("one");
unordered_map/unordered_multimap/unordered_set/unordered_multiset
Almost same usage as ordered container.
DIY sort
- For associative containers (like set) or
sort() , we can define and use a function object.
class cmp {
public:
bool operator ()(const string &a,const string &b) {
return (a.length() < b.length());
}
};
int main(){
set<string, cmp>myset{"11", "1", "111"};
return 0;
}
- If the type of elements is not structure pointer or class pointer, we can overloaded relational operators in the member function of elements:
class myString {
public:
myString(string a):str(a){}
string str;
bool operator < (const myString &m)const {
return str.length() < m.str.length();
}
};
int main(){
vector<myString>v{myString("11"), myString("1"), myString("111")};
sort(v.begin(), v.end());
return 0;
}
- For
sort() , we can define and use a normal function, too.
bool mycomp(string a, string b) {
return (a.length() < b.length());
}
int main(){
vector<string>v{"11", "1", "111"};
sort(v.begin(), v.end(), mycomp);
return 0;
}
Iterator
for (auto first = values.begin(); first != values.end(); ++first) {
cout << *first << " ";
}
mp.lower_bound(key0)->second
mp.upper_bound(key0)->second
mp.equal_range(key0)
auto it=values.begin();
auto it2=values.end();
int len=distance(it, it2);
advance(it,-3);
auto it3=it.prev(2);
auto it4=it.next(5);
|