标准库中的容器是泛型数据结构,特别适合保存数据集合。使用标准库时,几乎不需要使用标准C风格数组、编写链表或者设计堆栈。容器被实现为类模板,因此可利用任何满足以下基本条件的类型进行实例化。除array和bitset外,大部分标准库容器的大小灵活多变,都能实现自动增长或收缩,以容纳更多或更少的元素,和固定大小的旧的标准C风格数组相比,这有着巨大的优势。由于本质上标准C风格数组的大小是固定的,因此容易受到溢出的破坏。如果数据溢出,轻则导致程序崩溃,重则导致某些类型的安全攻击。使用标准库容器,程序遇到这种问题的可能性就会小很多。
标准库提供了16个容器,四大类
-
顺序容器
- vector
- deque
- list
- forward_list
- array
-
关联容器
- map
- multimap
- set
- multiset
-
无序关联容器或哈希表
- unordered_map
- unordered_multimap
- unordered_set
- unordered_multiset
-
容器适配器
- queue
- priority_queue
- stack
高精度乘除(一个高精度大数和一个小数)
vector<int> mul(vector<int> a, int b) { vector<int> c; int t = 0; //记录每一次运算后的临时值 for (int i = 0; i < a.size(); i++) { t += a[i] * b; c.push_back(t % 10);//将当前计算完成的值存入答案vector t /= 10;//记录进位 } while (t) c.push_back(t % 10), t /= 10; return c; } vector<int> div(vector<int> a, int b) { vector<int> c; bool is_first = false;//消除前导零 for (int i = a.size() - 1, t = 0; i >= 0; i--) { t = t * 10 + a[i]; int x = t / b; if (x || is_first) { is_first = true; c.push_back(x); } t %= b; } return vector<int>(c.rbegin(), c.rend()); }
大数比较
vector<int> max_vec(vector<int> a, vector<int> b) { if (a.size() > b.size()) return a; if (a.size() < b.size()) return b; if (a.size() == b.size()) {//当前值的位数相同 return vector<int>(a.rbegin(), a.rend()) > vector<int>(b.rbegin(), b.rend()) ? a : b; } }
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
在从大到小的排序数组中,重载lower_bound()和upper_bound()
lower_bound( begin,end,num,greater() ):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num,greater() ):从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。