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
Function | Description |
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的第一个元素的前面。 |