vector用法及通用函数总结
#include<bits/stdc++.h>
using namespace std;
vector<int>v;
vector<int>::iterator it1, it2, it;
vector<int>::iterator a, b;
1. .v.push_back()
2. v.pop_back()
3. v.front()
4. v.back()
5. reverse()
可对string,list,vector进行逆序
6. v.count()
7. v.count_if()
bool IsGreaterEx(int x)
{
return x > 3 ? true : false;
}
int main()
{
vector<int> vecInt;
vecInt.push_back(1);
vecInt.push_back(2);
vecInt.push_back(3);
vecInt.push_back(4);
vecInt.push_back(5);
cout << count(vecInt.begin(), vecInt.end(), 4) << endl;
cout << count_if(vecInt.begin(), vecInt.end(), IsGreaterEx) << endl;
return 1;
}
7. for_each()
for_each(a, b, [对该范围每个元素进行某种操作的函数])
8. find()
9. find_if()
int x;//要查找的元素
it1 = find(a, b, x);
it2 = find_if(a, b, bind2nd(greater<int>(), x));
//目前仅知道一个用于find_if的函数,即bind2nd
//两个函数返回的均是该容器对应类型的指针
cout << it1 - a << endl;//对应元素下标+1
cout << it2 - a << endl;//第一个大于x的元素下标+1
10. v.insert()
vector<int>v2;
v.insert(v2.begin(), [插入的元素]);//在容器起始位置插入单个元素
v.insert(v.begin(), v2.begin(), v2.end());//插入多个元素
v.insert(v.begin(), [插入的元素重复次数],[插入的元素]);//插入多个重复元素
11. remove()与erase
(1)vector中的remove的作用是将等于value的元素放到vector的尾部,
但并不减少vector的size
(2)vector中erase的作用是删除掉某个位置position或一段区域(begin, end)
中的元素,减少其size
两者详细用法见:
https://blog.csdn.net/weixin_36750623/article/details/92078198
(引用该大佬的文章)
12. v.size()
13. v.clear()
14. v.capacity()
15. v.resize()//定义容器容量,多则删,少则补
16. v.reverse()//扩充容量
17. v.swap(v2)
第一次写文章,之后会总结更多STL容器的更多相关函数和用法。
如有问题,感谢指正。