1. 什么是数组
- 数组的特点
- 数组是一系列元素;
- 数组中所有元素的类型都相同;
- 这组元素形成一个完整的集合。
1.1 声明和初始化静态数组
- 以下声明的所有数组都是静态数组,因为它们的长度在编译阶段就已确定
- 这种数组不能存储更多的数据
- 同时,即便有部分元素未被使用,它们占据的内存也不会减少
- 长度在执行阶段确定的数组被称为动态数组
int myNumbers [5] = {34, 56, -21, 5002, 365};
int myNumbers [5] = {};
int myNumbers [5] = {34, 56};
const int ARRAY_LENGTH = 5;
int myNumbers [ARRAY_LENGTH] = {34, 56, -21, 5002, 365};
int myNumbers [] = {2016, 2052, -525};
1.2 访问存储在数组中的数据
int myNumbers [5] = {34, 56, -21, 5002, 365};
cout << "First element at index 0: " << myNumbers[0] << endl;
1.3 修改存储在数组中的数据
myNumbers [3] = 2016;
2. 多维数组
2.1 声明和初始化多维数组
int solarPanels [2][3] = {{0, 1, 2}, {3, 4, 5}};
2.2 访问多维数组中的元素
- 值为205的元素的位置为[0][1],值为456的元素的位置为[2][1]
int threeRowsThreeColumns [3][3] = {{-501, 205, 2016}, {989, 101, 206},{303, 456, 596}};
3. 动态数组
- 为减少占用的内存,可使用动态数组,并在运行阶段根据需要增大动态数组
- 要使用动态数组类std::vector,需要包含头文件vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> dynArray (3);
dynArray[0] = 365;
dynArray[1] = -421;
dynArray[2]= 789;
cout << "Number of integers in array: " << dynArray.size() << endl;
cout << "Enter another element to insert" << endl;
int newValue = 0;
cin >> newValue;
dynArray.push_back(newValue);
cout << "Number of integers in array: " << dynArray.size() << endl;
cout << "Last element in array: ";
cout << dynArray[dynArray.size() - 1] << endl;
return 0;
}
4. C风格字符串
char sayHello[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'};
std::cout << sayHello << std::endl;
- 使用C语言编写的应用程序经常使用strcpy()等字符串复制函数、strcat()等拼接函数,还经常使用strlen()来确定字符串的长度
- 这些C风格字符串作为输入的函数非常危险,因为它们寻找终止空字符,如果程序员没有在字符数组末尾添加空字符,这些函数将跨越字符数组的边界
5. C++字符串:使用std::string
- std::string是动态的,在需要存储更多数据时其容量将增大
- 要使用C++字符串,需要包含头文件string
#include <iostream>
#include <string>
using namespace std;
int main() {
string greetStrings ("Hello std::string!");
cout << greetStrings << endl;
cout << "Enter a line of text: " << endl;
string firstLine;
getline(cin, firstLine);
cout << "Enter another: " << endl;
string secondLine;
getline(cin, secondLine);
cout << "Result of concatenation: " << endl;
string concatString = firstLine + " " + secondLine;
cout << concatString << endl;
cout << "Copy of concatenated string: " << endl;
string aCopy;
aCopy = concatString;
cout << aCopy << endl;
cout << "Length of concat string: " << concatString.length() << endl;
return 0;
}
Q&A
- 为何要不怕麻烦,去初始化静态数组的元素?
- 数组不同于其他类型的变量,除非进行初始化,否则它将包含无法预测的值,因为内存保留最后一次操作时的内容。通过初始化数组,可确保内存包含确定的值
- 需要基于前一个问题所说的原因初始化动态数组的元素吗?
- 实际上,不需要。动态数组相当聪明,无需将其元素初始化为默认值,除非应用程序要求数组包含特定的初始值
- 0,‘0’,‘\0’的区别
- 0 整数类型,占4个字节
- ‘0’ 用单引号括起来的是字符类型,ASCII 码值为48,占1个字节
- ‘\0’ 用单引号括起来是字符类型,前面有\,即使转义字符,ASCII 码值为0,占1个字节