参考书:C++ Primer Plus
数组的替代品:array 与 vactor
一、模板类vector
vector类似于string类,同属于STL(Standard Template Library, 标准模板库)中的一种自定义的数据类型,是一种动态数组。vector 是一种对象实体, 能够容纳许多其他类型相同的元素, 因此又被称为容器。可以在运行阶段设置vector对象的长度,可在末尾附加新元素,还可以再中间插入数据。
vector的基本知识:
1、包含头文件: #include
2、vector包含在名称空间std中,因此可使用using编译指令、using声明或std::vector。
3、使用不同语法指出存储的数据类型
4、使用不同语法指定元素数
5、vector分配空间策略:vector会分配一些额外的空间以适应可能的增长,因为存储空间比实际需要的存储空间更大。不同的库采用不同的策略权衡空间的使用和重新分配。但是无论如何,重新分配都应该是对数增长的间隔大小,以至于在末尾插入一个元素的时候是在常数时间的复杂度完成的。
6、vector类的功能比数组强大,但付出的代价是效率稍低。如果需要长度固定的数组,则尽量不要选择使用容器。
示例:
#include
#include
using namespace std ;
int main(){
vector vi ; // create a zero-size array of int
int n ;
cin >> n ;
vector vd(n); //create an array of n double
}
其中,vi是一个vector
声明模板: vector
二、模板类array
与数组一样,array对象长度也是固定的,也使用栈(静态内存分配),而不是自由存储区,因此其效率与数组相同,但更方便,更安全。
array的基本知识:
1、包含头文件#include
2、array的创建语法:
#include
#include
using namespace std;
int main(){
array ai; //create array objecrt of 5 ints
array ad = {1.2 , 2.1 , 5.4 , 4.3};
}
声明模板:array
三、数组、vector对象和array对象实例
#include
#include
#include
using namespace std;
int main(){
//c,original C++
double a1[4] = {1.2 , 2.4 , 3.6 , 4.6} ;
//C++98STL
vector a2(4) ;
//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 and initialize array odject
array a3 = {3.14 , 2.72 , 1.62 , 1.41} ;
array a4 ;
a4 = a3 ; //valid for array objects of same size
//use array notation
cout << "a1[2]: " << a1[2] << " at " << &a1[2] << endl ;
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 ;
return 0;
}
运行结果:
程序说明:
1、无论是数组,vector还是array,都可以使用标准数组表示法来访问各个元素
2、从地址可知,array对象和数组存储在相同的区域(即栈)中,而vector对象存储在另一个区域(自由存储区或堆中)
3、可以将一个array对象赋给另一个array对象(值复制),而数组则需要逐个元素复制