1.vector 初始化
vector<int> nums;
vector<int> nums{1,2,3};
vector<int> nums(n,1);
vector<vector<int>> nums(m,vector<int>(n,1));
1.1 增删查改
int n = nums.size();
nums.push_back(1);
// emplace_back 省去了拷贝和移动元素过程,大多时候更快
nums.emplace_back();
nums.erase(nums.begin());
nums.erase(nums.begin(),nums.end()); // 删除一段区间
// 这个删完,位置自动前移
/*
vector<int> nums{0,1,2,3,4,5};
cout<<&nums[0]<<endl; // 0x7fe47b405a60
cout<<&nums[1]<<endl; // 0x7fe47b405a64
nums.erase(nums.begin());
cout<<&nums[0]<<endl; // 0x7fe47b405a60
cout<<&nums[1]<<endl; // 0x7fe47b405a64
cout<<&nums<<endl;
*/
nums.pop_back();
2.string
// 转 int
string s = "2147483647";
for (int i = 0; i < n; ++i){
nums[i] = s[i] - '0';
}
// //返回从索引pos开始,长度为len的子字符串
string s_child = s.substr(size_t pos, size_t len)
push_back()
pop_back()
string str = "hello";
str.insert(1,"Hahah");//在原串下标为1的字符e前插入字符串s
str.insert(4,5,'c');//在原串下标为4的字符o前插入5个字符c
string s2 = "weakhaha";
str.insert(0,s2,1,3);//将字符串s2从下标为1的e开始数3个字符,分别是eak,插入原串的下标为0的字符h前
3.deque
push_front();
push_back();
pop_back();
pop_front();
4.unordered_set
5.unordered_map
key 唯一,unordered_nultimap key 可以冗余。
unordered_map<int, string> mp;
//查
iterator find(const int& key);
//增删
pair<int, string> kv(1,"one");
mp.insert(kv);
//1:迭代器遍历
unordered_map<int, string>::iterator it = mp.begin();
while (it != mp.end())
{
cout << it->first << ":" << it->second << " ";
it++;
}
mp.erase(1); // 根据key删除
//insert(key, value);
//erase(key, value);
6.unordered_set
unordered_set<int> s;
/*插入*/
s.insert(1);
s.insert(-2);
s.insert(1);
s.insert(5);
s.insert(3);
s.insert(-2);
s.insert(6);
s.insert(4);
/*遍历*/
unordered_set<int>::iterator it = s.begin();
while (it != s.end())
{
cout << *it << " ";
it++;
}
cout << endl;//1 5 -2 3 6 4
7. map 和 unordered_map 区别
unordered_map | map | |
---|---|---|
底层数据结构 | hash | rbtree |
是否有序 | no | yes |
查找的效率 | O(1) | O(logN) |
迭代器类型 | 单向 | 双向 |