c++ vector用法是什么


本文摘自PHP中文网,作者coldplay.xixi,侵删。

c++ vector用法是:1、创建vector对象;2、尾部插入数字;3、使用下标访问元素;4、使用迭代器访问元素;5、插入元素;6、)删除元素等等。

在c++中,vector是一个十分有用的容器,c++ vector用法是:

1、基本操作

(1)头文件#include<vector>.

(2)创建vector对象,vector<int> vec;

(3)尾部插入数字:vec.push_back(a);

(4)使用下标访问元素,cout<<vec[0]<<endl;记住下标是从0开始的。

(5)使用迭代器访问元素.

1

2

3

vector<int>::iterator it;

for(it=vec.begin();it!=vec.end();it++)

    cout<<*it<<endl;

(6)插入元素:

1

vec.insert(vec.begin()+i,a);

在第i+1个元素前面插入a;

(7)删除元素:

1

vec.erase(vec.begin()+2);

删除第3个元素

1

vec.erase(vec.begin()+i,vec.end()+j);

删除区间[i,j-1];区间从0开始

(8)向量大小: vec.size();

(9)清空: vec.clear();

2、vector的元素不仅仅可以使int,double,string,还可以是结构体,但是要注意:结构体要定义为全局的,否则会出错。下面是一段简短的程序代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

#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>

1

reverse(vec.begin(),vec.end());

将元素翻转(在vector中,如果一个函数中需要两个迭代器,一般后一个都不包含.)

(2)、使用sort排序:需要头文件#include<algorithm>,

1

sort(vec.begin(),vec.end());

(默认是按升序排列,即从小到大).

可以通过重写排序比较函数按照降序比较,如下:

定义排序比较函数:

1

2

3

4

bool Comp(const int &a,const int &b)

{

    return a>b;

}

调用时:sort(vec.begin(),vec.end(),Comp),这样就降序排序。

相关学习推荐:C视频教程

以上就是c++ vector用法是什么的详细内容!

相关阅读 >>

C++数组初始化的种类有哪些

C++实现在二维数组中的查找

C++中判断重载方法的依据是什么

在c/C++中如何使用extern关键字

c/C++函数如何返回多个值?(代码示例)

案例分享C++ map的使用和 查找性能测试

C++是什么意思

详解C++ 多态公有继承

C++类型如何进行转换

C++学习之new()和malloc()函数

更多相关阅读请进入《C++》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...