C++中的STL之vector的超详细基本用法
来源:互联网 发布:周灏 数据财经新浪网 编辑:程序博客网 时间:2024/06/05 20:31
在c++中,vector是一个十分有用的容器,下面对这个容器做一下总结。
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),这样就降序排序。
vector初始化的几种方法:
C++ Reference对于memset的定义为:
void * memset ( void * ptr, int value, size_t num );
对int类型的内存区域进行初始化,ptr的类型是int*,举例说明一下:
1. 将内存初始化为0
memset(ptr,0,sizeof(ptr));2. 将内存初始化为-1
memset(ptr,0xff,sizeof(ptr));
因为按照字节进行填充,那么value值为0xff,将会把内存的每个字节都填充为0xff,则int值的区域为全1,那么int值就是-1。
3. 将内存初始化为极大值
memset(ptr,0x3f,sizeof(ptr));
这段初始化代码初始出来的int值大小是1061109567
- C++中的STL之vector的超详细基本用法
- STL之vector的基本用法
- [C++::STL]之vector的用法
- STL之Vector(一):Vector的基本用法
- STL之vector的用法
- STL vector基本用法
- [STL] vector基本用法
- [STL] vector基本用法
- STL中vector的基本用法范例
- STL 中的vector用法
- STL中的vector用法
- C++stl vector 用法
- [C++] Vector 中的基本用法(一)
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- 1.3 构造函数
- Android 调用第三方地图类App (高德 百度 百度网页版)
- mmseg4j 中文分词简单代码实例
- linux 安装jdk1.7
- Nodejs:Passport验证用户名密码(不完全)
- C++中的STL之vector的超详细基本用法
- qt与html实现移动效果
- iOS 随机数生成
- 自定义scrollview实现类似地图横向纵向同时滚动
- Tomcat配置的问题出现Error Creating Deployment原因及解决办法
- WOT 2017全球创新技术峰会5.5折专享票
- hadoop2.x eclipse插件编译
- 聚类算法之DBSCAN(具有噪声的基于密度的聚类方法)
- jquery 点击同类标签获取不同值