Vector的概念
vector跟数学上的向量并没有任何关系,仅仅是一个名字,千万别翻译成中文,最好叫它动态数组。
Vector的属性
vector优异性能就是配置比其所容纳的元素所需更多的内存,一般在使用vector之前,就先预留足够空间,以避免二次分配,这样可以使vector的性能达到最佳。因此元素个数_Count是个远比元素值 _Val重要的参数,因此当构造一个vector时,首要参数一定是元素个数。
vector是一个动态数组
vector可以不断添加数据,不像是数组,定义后就不能修改大小
vector是一个类模板(class template)
vector对象的操作 vector<T> :: size_type
vector下标操作不添加元素
由于vector是一个类模板,因此,需要使用尖括号,并在尖括号里面。
例如:vector<int> ivec;代表创建一个动态数组vector,保存类型为int的数据
vector<double>;代表创建一个动态数组double,保存类型为double的数据
vector<string>;代表创建一个动态数组string,保存类型为string的数据
vector<Dog>;代表创建一个动态数组Dog,保存类型为Dog的数据
示例代码:
#include<iostream>
#include<vector>
#include<string>
#include"Dog.h"
using namespace std;
using std::vector;//vector属于std命名空间下
void main()
{
vector<int> ivec;
vector<double> ivec_double;
vector<string> ivec_string;
vector<Dog> ivec_Dog;
vector<int> a;//空容器
vector<int> b(10,2);//该容器中有10个2
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
b.push_back(10);
b.push_back(11);
b.push_back(12);
cout << a.size() << endl;
cout << b.size() << endl;
}
输出:
4
13
遍历Vector
向量vector(动态数组)有自己的size_type,向量的遍历:
for(vector<int>::size_type i = 0;i != a.size();i++)
{
cout << a[i] << endl;
}
向量与向量之间进行参数传递:
vector<int> vv1;
//v1的参数传递进入v2
vv1.push_back(10);
vv1.push_back(11);
vv1.push_back(12);
vector<int> v2(vv1);
赋值
对向量中某一脚标对应的内存vector进行赋值
vector<int> vec;
vec[0] = "hello";//对新建的vec向量变量的第0个元素进行赋值操作。
不能对未分配内存空间的vector进行cin,比如cin >> vv1[i];是错误的,因为vv1中并没有任何数,是一个空向量。
#include<iostream>
#include<vector>
#include<string>
#include"Dog.h"
using namespace std;
using std::vector;//vector属于std命名空间下
void main()
{
vector<int> vv1;
int k;
vector<int> v2;
//赋值
for(vector<int>::size_type i = 0;i != 5; i++)
{
cin >> k;
vv1.push_back(k);
}
cout << "显示vector里面的数据:" << endl;
for(vector<int>::size_type i = 0;i != 5; i++)
{
cout << vv1[i] << endl;
}
}