C++ vector容器
来源:互联网 发布:雅米网络兼职骗过的 编辑:程序博客网 时间:2024/06/05 03:05
1、基本操作
(1)头文件#include<vector>.
(2)创建vector对象,vector<int> vec;
(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、举例说明
vector的元素不仅仅可以使int,double,string,还可以是结构体,但是要注意:结构体要定义为全局的,否则会出错。下面是一段简短的程序代码:
复制代码
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
typedef struct rect
{
int id;
int length;
int width;
//对于向量元素是结构体的,可在结构体内部定义比较函数,下面按照id,length,width升序排序。
bool operator< (const rect &a) const
{
if(id!=a.id)
return id<a.id;
else
{
if(length!=a.length)
return length<a.length;
else
return width<a.width;
}
}
}Rect;
int main()
{
vector<Rect> vec;
Rect rect;
rect.id=1;
rect.length=2;
rect.width=3;
vec.push_back(rect);
vector<Rect>::iterator it=vec.begin();
cout<<(*it).id<<' '<<(*it).length<<' '<<(*it).width<<endl;
return 0;
}
复制代码
3、算法
(1) 使用reverse将元素翻转:需要头文件#include<algorithm>
reverse(vec.begin(),vec.end());将元素翻转(在vector中,如果一个函数中需要两个迭代器,
一般后一个都不包含.)
(2)使用sort排序:需要头文件#include<algorithm>,
sort(vec.begin(),vec.end());(默认是按升序排列,即从小到大).
可以通过重写排序比较函数按照降序比较,如下:
定义排序比较函数:
bool Comp(const int &a,const int &b)
{
return a>b;
}
调用时:sort(vec.begin(),vec.end(),Comp),这样就降序排序。
//如果排序条件不止一个呢?
extern bool CompareByGold(PropTypeInfoEX left, PropTypeInfoEX right)//根据金币来比较 先根据金币来比,如果金币相同,再根据用户ID来比较 这里是从小到大来进行排序;
{
return (left.money < right.money) || ((left.money == right.money) && left.propid < right.propid);
}
- 【c++】容器vector
- C++-vector(容器)
- 【C++】实现容器Vector
- C++vector(容器)用法
- 【C++】顺序容器 Vector 注意事项
- vector 容器类 (C++)
- C++vector容器用法详解
- C++vector基础容器2.0
- C++STL之vector容器
- C串分隔子串到vector容器内
- C++STL容器技术之Vector
- 初学者学习C++STL之vector容器
- C++STL中vector容器的用法
- 【C++】顺序容器之vector用法
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- C模板实现STL容器中的vector
- webpack使用
- android毛玻璃背景简单实现
- Android端口服务类型笔记
- JAVA企业面试题精选 数据库31-40
- MyBatis 传List参数 nested exception is org.apache.ibatis.binding.BindingException: Parameter 'idList' n
- C++ vector容器
- Linux线程池实现--基于Select复用的回射服务器
- 201503-2
- pip下载速度慢
- 刚建spingboot项目访问时候出现的错误
- 201609-1
- 蛇形填数
- AB1601LED之pwm
- 过滤器解决JSP中英文编码