数组
序言:
尽管现代C++仍然支持数组与指针类型,但是,现代的C++程序应尽量使用vector和迭代器类型。设计良好的程序只有在强调速度时才在类的实现内部使用数组和指针!
即:只有当性能测试表明使用vector无法达到必要的速度时,才使用数组!
正文:
1、数组定义中的类型可以是内置类型或类类型;除了引用之外,数组元素的类型可以是任意的复合类型。没有所有元素都是引用的数组*^_^*
2、非const变量以及直到运行阶段才知道其值的const对象不能用于指定数组的维数!
- const int n = get_size();
- int arr[n]; //ERROR
- int arr[get_size()]; //ERROR
- int arr_size = 110;
- int arr[arr_size]; //EROR
3、显式初始化数组元素
- const unsigned array_size = 3;
- int ia[array_size] = {0,1,2};
- int ia[] = {0,1,2};
4、没有显示提供元素初值,则数组会像普通变量一样初始化
1)在函数体外定义的内置元素数组,其元素均初始化为0;
2)在函数体内定义的内置元素数组,不进行初始化!
3)如果是类类型,则自动调用默认构造函数!
5、如果只是初始化了部分数组元素,那么剩下的元素,如果是内置类型则初始化为0,若是类类型,则调用他的默认构造函数。
- const int arr_size = 5;
- int arr[arr_size] = {1,2};
- for (int i = 0;i < arr_size; ++i)
- {
- cout << arr[i] << ' ';
- }
- cout << endl;
- string arr2[arr_size] = {"Hello","World"};
- for (int i = 0;i < arr_size; ++i)
- {
- cout << arr2[i] << endl;
- }
6、特殊的字符数组!
- char ca1[] = {'C','+','+'}; //没有结束符,size = 3,但是用strlen测试不出正确的结果!
- char ca2[] = "C++"; //自动添加了NULL结束符,size = 4
- char ca3[] = {'C','+','+','\0'}; //显式添加了NULL结束符
- char ca4[6] = "Daniel"; //编译时错误!
7、不允许数组直接复制或赋值!
- //P98 习题4.3 下列语句是否正确
- vector<int> ivec = {0,1,2,3,4}; //ERROR
- int ia1[7] = {0,1,2,3,4,5,6};
- int ia2 = ia1; //ERROR
8、数组下标的正确类型是size_t
- //示例1
- int main()
- {
- const size_t arr_size = 10;
- int ia[arr_size];
- for (size_t i = 0;i < arr_size; ++i)
- {
- ia[i] = i + 1;
- }
- return 0;
- }
- //示例2
- int main()
- {
- const size_t arr_size = 7;
- int arrSor[] = {0,1,2,3,4,5,6};
- int arrDes[arr_size];
- for (size_t index = 0;index < arr_size; ++index)
- {
- arrDes[index] = arrSor[index];
- }
- return 0;
- }
9、一旦引用了越出数组或其他类似数据结构的边界的元素时,就会导致缓冲区溢出错误!
- //P100 习题4.7(2)
- int main()
- {
- vector<int> ivec1;
- for (int i = 0;i != 10; ++i)
- {
- ivec1.push_back(i);
- }
- vector<int> ivec2(ivec1);
- for (vector<int>::iterator iter = ivec2.begin(); iter != ivec2.end(); ++iter)
- {
- cout << *iter << endl;
- }
- }
- //习题4.8(1)
- int main()
- {
- const int arr_size = 7;
- int arr1[arr_size] = {1,2,3};
- int arr2[arr_size] = {4,5,6};
- for (int i = 0;i != arr_size; ++i)
- {
- if (arr1[i] != arr2[i])
- {
- cout << "arr1 is not equal to arr2" << endl;
- break;
- }
- }
- return 0;
- }
- //(2)
- int main()
- {
- vector<int> ivec1;
- vector<int> ivec2;
- int value;
- while (cin >> value)
- {
- ivec1.push_back(value);
- }
- while (cin >> value)
- {
- ivec2.push_back(value);
- }
- if (ivec1 == ivec2)
- {
- cout << "ivec1 is equal to ivec2" << endl;
- }
- else
- {
- cout << "ivec1 is not equal to ivec2" << endl;
- }
- return 0;
- }
本文借鉴:http://blog.csdn.net/zjf280441589/article/details/23021813