自定义结构体排序
struct Node{
int a, b;
bool operator<(const Node& other)const{
return a < other.a;//升序:从小到大
//return a < other.a;//降序:从大到小
}
};
vector<Node>vc;
sort(vc.begin(), vc.end());
初始化
vector<int> vec(len, x);//创建一个长为n的vector,并将所有元素初始化为某一定值x
vector<int>father = {0, 1, 1, 2, 3, 5, 2, 1};//列举赋值
vector<int>ac(father);//完全继承式初始化
vector<int>vc(father.begin()+1, father.end()-1);//节选继承式初始化
增
vc.push_back(4);
vc.insert(vc.begin()+2, 666);//2号位插入666
vc.insert(vc.end(), fathers.begin(), fathers.end()); //插入完整fathers
删
//删除所有的1
vc.erase(remove(vc.begin(), vc.end(), 1), vc.end());
改
sort(vc.begin(), vc.end());
fill(vc.begin(), vc.end(), -1)//代码执行过程中将所有元素更新为某一值x
查
vector<int>::iterator itor = vc.begin();
for(; itor != vc.end(); itor++)
{
cout<<*itor<<" ";
}
方法总汇:
#include<bits/stdc++.h>
using namespace std;
int main()
{
//初始化
vector<int>father = {0, 1, 1, 2, 3, 5, 2, 1};//列举赋值
vector<int>ac(father);//完全继承式初始化
vector<int>vc(father.begin()+1, father.end()-1);//节选继承式初始化
//增
vc.push_back(4);
vc.insert(vc.begin()+2, 666);//2号位插入666
//删
int sz = vc.size();
vc.erase(remove(vc.begin(), vc.end(), 1), vc.end());//删除所有的1
//解释:remove将所有1移到最后,并返回一个位置,使remove,vc.end()之间是所有的1
cout<<"initial size: "<<sz<<endl;
cout<<"size after erase: "<<vc.size()<<endl;
//改
sort(vc.begin(), vc.end());
//查
//遍历
vector<int>::iterator itor = vc.begin();
for(; itor != vc.end(); itor++)
{
cout<<*itor<<" ";
}
cout<<"\n第0号位置: "<<vc.front()<<endl;
cout<<"第2号位置: "<<vc.at(2)<<endl;
cout<<"最后一位值: "<<vc.back()<<endl;
}
运行结果如下:
//说明:本文精炼,挑选了各功能最常用的实现方式,想了解更多的朋友可以参考文章:
C++ vector类成员函数介绍_c++vector函数-CSDN博客
~希望对你有帮助~