[C++] STL的vector模板类

Note :STL = Standard Template Library 标准模板库

Vector

首先,要使用vector模板类,要先在cpp文件中加入

#include<vector>

在计算中,矢量vector对应数组

#vector支持随机访问,意味着可以直接通过索引得到值

eg.vector<int> A;  A[8];

要创建vector模板对象,可以使用<type>表示法来指出要使用的类型。

<int><double><string>...

初始化vector

#include<vector>
#include<iostream>
using namespace std;
//method1, we need a vector of 8 ints
vector<int> MyVector(8);
//method2, we need a vector of n ints.
int n;
cin >> n;
vector<int> MyVector2(n);
//method3, we want a vector which is the copy of another one.
vector<int> MyVector3(MyVector2);
//method4, we want a vector which contains n (value)s.
vector<int> MyVector4(n, 8);

Vector的方法

Assume we have a vector scores

FunctionDescription
size()

返回容器中元素数目

scores.size()

swap()

交换两个容器的内容

begin()

返回一个指向容器中第一个元素的迭代器

end()返回一个表示超过容器尾的迭代器
push_back()

将元素添加到矢量末尾

scores.push_back(temp)

erase()

删除矢量中给定区间的元素(接收两个迭代器参数,第一个迭代器指向区间的起始处,第二个迭代器位于区间终止处的后一个位置,意味着以下操作删除begin()和begin()+1指向的元素)

scores.erase(scores.begin(),scores.begin()+2)

insert()

插入元素,接收三个迭代器参数,第一个参数指定了新元素的插入位置,第二个和第三个迭代器参数定义了被插入区间(该区间通常是另一个容器对象的一部分)

vector<int> old;

vector<int> new;

...

old.insert(old.end(), new.begin()+1, new.end())

将vector new中除第一个元素以外的所有元素插入到vector old的第一个元素的前面。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值