模板类 vector 和 array 是数组的替代品。
4.10.1 模板类 vector
特点:
①它是一种动态数组,可以在运行阶段设置 vector 对象的长度。
②它是使用 new 创建动态数组的替代品。
③vector类使用 new 和 delete 来管理内存,但是这种工作是自动完成的。
④较之数组和array类而言,vector类的效率稍低。
语法规则:
vector < typeName> arrayName (Asize);
注释:typename: 数组类型名 arrayName:数组名 Asize: 数组长度(可以是常量也可以是变量)
例如:声明创建一个数组名为age的vector对象,它可以存储10个类型为整型int的元素: vector < int> age (10);
说明:
① 要使用 vector 对象,必须包含头文件 vector。 #include < vector>
② vector 对象的长度 Asize 既可以是常量也可以是变量,体现了动态数组的特点。(数组长度只能是常量)
例如: 设置一个长度为 n 的动态数组
int n;
cin >> n;
vector <double> vd( n );
4.10.2 模板类 array
特点:
①要使用 array 对象,必须包含头文件 array。 #include < array>
②array类用于长度固定的数组,与数组效率相同,长度不可更改。
③对于长度相同(数组元素个数相同)的array对象,可以相互赋值,而数组必须逐元素赋值。
例如:
array<int,4> a1={1,2,3,4}
array<int,4> a2;
a2 = a1;
语法规则:
array < typeName,Asize> arrayName;
注释:typename: 数组类型名 arrayName:数组名 Asize: 数组长度(只能是常量)
例如:声明创建一个数组名为age的array对象,它可以存储10个类型为整型int的元素: array < int,10> age;
程序清单 4.24 choices.cpp
// Created by 刘伟 on 15/5/31.
// Copyright (c) 2015年 刘伟. All rights reserved.
//C++ primer plus
//程序清单4.24 choices.cpp
//choices.cpp -- array variations
#include<iostream>
#include<vector> // STL C++98
#include<array> // C++11
using namespace std;
int main()
{
// C, original C++
double a1[4] = {1.2, 2.4, 3.6, 4.8};
// C++98 STL
int n;
cout << "You can set the value of the vector's length!" << endl;
cout << "Enter the length of vector, n = ";
cin >> n;
vector<double> a2(n); // create vector with 4 elements
// no simple way to initialize in C98
a2[0] = 1.0 / 3.0;
a2[1] = 1.0 / 5.0;
a2[2] = 1.0 / 7.0;
a2[3] = 1.0 / 9.0;
// C++11 -- create an d initialized array object
array<double, 4> a3 = {3.14, 2.72, 1.62, 1.41};
array<double, 4> a4;
a4 = a3;
// valid for array objects of same size(对于array对象,只要长度相同都可以相互赋值,而不用像数组那样诸逐个元素赋值)
// use array notation
cout << "a1[2]: " << a1[2] << " at " << &a1[2] << endl;
cout << "a1[3]: " << a1[3] << " at " << &a1[3] <<" "<< & *(a1 + 3) <<endl;
// arrayName[i] <=> *(arrayName + i)
cout << "a2[2]: " << a2[2] << " at " << &a2[2] << endl;
cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl;
// misdeed
a1[-2] = 20.2; // *(a1 - 2) = 20.2
cout << "a1[-2]: " << a1[-2] <<" at " << &a1[-2] << endl;
cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl;
return 0;
}
程序输出示例:
You can set the value of the vector’s length!
Enter the length of vector, n = 4
a1[2]: 3.6 at 0x7fff5fbff830
a1[3]: 4.8 at 0x7fff5fbff838 0x7fff5fbff838
a2[2]: 0.142857 at 0x100200070
a3[2]: 1.62 at 0x7fff5fbff670
a4[2]: 1.62 at 0x7fff5fbff650
a1[-2]: 20.2 at 0x7fff5fbff810
a3[2]: 1.62 at 0x7fff5fbff670
a4[2]: 1.62 at 0x7fff5fbff650
Program ended with exit code: 0
程序说明:
从地址可知:array 对象和数组存储在相同的内存区域(即是栈)中,而 vector 对象存储在另一个区域(自由存储区域或栈)中。