1.模板类array:
这个是C++ 11新增的。下面的声明创建一个名为arr的array对象,它包含n_elem个类型为typename的元素:
array<typeName, n_elem> arr ;
与创建vector对象不同的是,n_elem不能是对象
2.对于一般的数组,C++和C语言都不会去检查越界错误,就像这样:
a1[-2] = 20.2 ;
cout << "a1[-2]: " << a1[-2] << " at " << &a1[-2] << endl ;
cout << "-----------------------------------------------------------------------------" << endl << endl ;
a2[-2] = 0.5 ;
a3[200] = 1.4 ;
cout << "a2[-2]: " << a2[-2] << " at " << &a2[-2] << endl ;
cout << "a3[200]: " << a3[200] << " at " << &a3[200] << endl ;
运行结果:
a1[-2]: 20.2 at 0x7ffc93cb0f60
-----------------------------------------------------------------------------
a2[-2]: 0.5 at 0x5569ec44cea0
a3[200]: 1.4 at 0x7ffc93cb15d0
但是vector和array都提供了成员函数at( ),使用该函数时将在运行期间捕获非法索引,而程序也将中断,不过在编译期间还是看不出来。例如:
#include <iostream>
#include <vector>
#include <array>
using namespace std ;
int main()
{
vector<double> a2(4) ;
a2[0] = 1.0/3.0 ;
a2[1] = 1.0/5.0 ;
a2[2] = 1.0/7.0 ;
a2[3] = 1.0/9.0 ;
array<double, 4> a3 = {3.14, 2.72, 1.62, 1.41} ;
array<double, 4> a4 ;
a4 = a3 ;
a2.at(-2) = 9.65 ;
cout << "a2[-2] = " << a2[-2] << endl ;
a3.at(200) = 5.43 ;
cout << "a3[200] = " << a3[200] << endl ;
a4.at(-5) = 6.22 ;
cout << "a4[-5] = " << a4[-5] << endl ;
return 0 ;
}
运行结果:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 18446744073709551614) >= this->size() (which is 4)
Aborted (core dumped)
3.在声明vector对象时要注意,下面两种直接初始化都不可取:
(1)
test1.cpp: In function ‘int main()’:
test1.cpp:10:19: error: expected ‘,’ or ‘;’ before ‘=’ token
10 | vector<int> c(5) = {1, 3, 5, 7, 9} ;
| ^
(2)
test1.cpp: In function ‘int main()’:
test1.cpp:10:19: error: expected ‘,’ or ‘;’ before ‘{’ token
10 | vector<int> c(5) {1, 3, 5, 7, 9} ;
| ^
像这样就行了:(不仅对int类型,对其他类型也是这样)
vector<int> c = {1, 3, 5, 7, 9} ;
4.如果你想利用模板类array来构造字符数组的话,这样是不可取的:
test2.cpp:9:22: error: conversion from ‘const char [13]’ to non-scalar type ‘std::array<char, 20>’ requested
9 | array<char, 20> c = "cheeseburger" ;
| ^~~~~~~~~~~~~~
只能这样了:
array<char, 20> c = {'c', 'h', 'e', 'e', 's', 'e', 'b', 'u', 'r', 'g', 'e', 'r'} ;
5.使用new来创建动态数组:
int * dyn = new int [size] ;
6.如果想要在C++程序中不使用using,但还想去使用vector对象、array对象和string对象,该怎么办呢?下面的方法可参考:
#include <vector>
#include <array>
#include <string>
int main()
{
const int n {10} ;
std::vector<std::string> a(n) ;
std::array<std::string, n> b ;
}
7.像下面这样:
char bird[11] = "Mr. Cheeps" ;
char fish[] = "Bubble" ;
用引号括起的字符串隐式的包括结尾的空字符,因此不用显式的包括它
8.“S"不是字符常量,它表示的是两个字符(‘S’和’\0’)组成的字符串,更糟的是,"S"实际上表示的是字符串所在的内存地址。下面的编译错误:
test4.cpp:17:20: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
17 | char shirt_size = "S" ;
| ^~~
| |
| const char*