-
Declaration:
vector<int>v; (creates an empty vector of integers)
-
Size:
int size=v.size();//当前v的长度
-
Pushing an integer into a vector:
v.push_back(x);(where x is an integer.The size increases by 1 after this.)
-
Popping the last element from the vector:
v.pop_back(); (After this the size decreases by 1)
-
v.empty()
判断是否为空
-
v.clear()
-
清空
-
Sorting a vector:
sort(v.begin(),v.end()); (Will sort all the elements in the vector)//可以加个cmp函数实现降序
-
erase(int position):
Removes the element present at position.<br> Ex: v.erase(v.begin()+4); (erases the `$5{th}$` element of the vector v)
erase(int start,int end):
Removes the elements in the range from start to end inclusive of the start and exclusive of the end. Ex:v.erase(v.begin()+2,v.begin()+5);(erases all the elements from the third element to the fifth element.)
lower_bound/upper_bound example
#include <iostream> // std::cout #include <algorithm> // std::lower_bound, std::upper_bound, std::sort #include <vector> // std::vector int main () { int myints[] = {10,20,30,30,20,10,10,20}; std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20 std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30 std::vector<int>::iterator low,up; low=std::lower_bound (v.begin(), v.end(), 20); // ^ up= std::upper_bound (v.begin(), v.end(), 20); // ^ std::cout << "lower_bound at position " << (low- v.begin()) << '\n'; std::cout << "upper_bound at position " << (up - v.begin()) << '\n'; return 0; }
-
1.push_back 在数组的最后添加一个数据
-
2.pop_back 去掉数组的最后一个数据
-
3.at 得到编号位置的数据
-
4.begin 得到数组头的指针
-
5.end 得到数组的最后一个单元+1的指针
-
6.front 得到数组头的引用
-
7.back 得到数组的最后一个单元的引用
-
8.max_size 得到vector最大可以是多大
-
9.capacity 当前vector分配的大小
-
10.size 当前使用数据的大小
-
11.resize 改变当前使用数据的大小,如果它比当前使用的大,者填充默认值
-
12.reserve 改变当前vecotr所分配空间的大小
-
13.erase 删除指针指向的数据项
-
14.clear 清空当前的vector
-
15.rbegin 将vector反转后的开始指针返回(其实就是原来的end-1)
-
16.rend 将vector反转构的结束指针返回(其实就是原来的begin-1)
-
17.empty 判断vector是否为空
-
18.swap 与另一个vector交换数据
c++ vector容器的用法
最新推荐文章于 2024-07-28 23:14:56 发布