在c++中,vector是一个十分有用的容器,下面对这个容器做一下总结。
1 基本操作
(1)头文件#include
(2)创建vector对象,vector
(3)尾部插入数字:vec.push_back(a);
(4)使用下标访问元素,cout<<vec[0]<<endl;记住下标是从0开始的。
(5)使用迭代器访问元素.
vector<int>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
cout<<*it<<endl;
(6)插入元素: vec.insert(vec.begin()+i,a);在第i+1个元素前面插入a;
(7)删除元素: vec.erase(vec.begin()+2);删除第3个元素
vec.erase(vec.begin()+i,vec.end()+j);删除区间[i,j-1];区间从0开始
(8)向量大小:vec.size();
(9)清空:vec.clear();
2.下面是我自己测试的一些用法,仅供参考:
#include<iostream>
#include<vector>
#include<stdio.h>
using namespace std;
typedef struct A{
int id;
int length;
int width;
//对于一些向量的元素是结构体的,可以在结构体里面定义比较函数,下面按照id,length,width升序排序
bool operator<(const A &a)const{
if(id!=a.id)
return id<a.id;
else{
if(length!=a.length)
return length<a.length;
else
return width<a.width;
}
}
}A;
int main(){
vector<int> vi;
vi.push_back(12);//这个是从向量的末尾插入元素
vi.push_back(13);
vi.pop_back();//从末尾删除元素
vi.push_back(32);
vector<int>::iterator iter;//通过迭代器遍历vector中的元素
for(iter=vi.begin();iter!=vi.end();iter++){
cout<<*iter<<" ";
}
cout<<endl;
vi.insert(vi.begin()+1,2);//在指定的位置插入元素
for(iter=vi.begin();iter!=vi.end();iter++){
cout<<*iter<<" ";
}
cout<<endl;
vi.erase(vi.begin()+1);//删除指定位置的元素
for(iter=vi.begin();iter!=vi.end();iter++){
cout<<*iter<<" ";
}
cout<<endl;
vi.erase(vi.begin()+1,vi.end());//这个是删除指定区间的元素,区间为【i,j]
for(iter=vi.begin();iter!=vi.end();iter++){
cout<<*iter<<" ";
}
cout<<endl;
//向量的测试
vector <A> vec;
A a;//初始化一个结构体元素
a.id=1;
a.length=2;
a.width=3;
vec.push_back(a);//插入进向量中
vector<A>:: iterator ite;
ite=vec.begin();
cout<<(*ite).id<<" "<<(*ite).length<<" "<<(*ite).width<<endl;
}
3.下面这些是一些简单的算法,还有其他的算法如果需要的话请参考《STL源码剖析》
(1) 使用reverse将元素翻转:需要头文件#include
reverse(vec.begin(),vec.end());将元素翻转(在vector中,如果一个函数中需要两个迭代器,
一般后一个都不包含.)
(2)使用sort排序:需要头文件#include
sort(vec.begin(),vec.end());(默认是按升序排列,即从小到大).
可以通过重写排序比较函数按照降序比较,如下:
定义排序比较函数:
bool Comp(const int &a,const int &b)
{
return a>b;
}
原文链接: https://www.cnblogs.com/Kobe10/p/5533559.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/234069
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!