数组
内容简介
数组用于存放一组类型相同的数据。学习 C++ 时优先掌握 std::array 和 std::vector,再了解 C 风格数组的连续内存和数组退化,这对理解指针很重要。
用法
C++ 常用容器
#include <array>
#include <iostream>
#include <vector>
int main()
{
std::array<int, 3> fixed_scores = {90, 80, 70};
std::vector<int> scores = {90, 80, 70};
scores.push_back(100);
for (int score : scores) {
std::cout << score << " ";
}
return 0;
}C 风格数组
#include <stdio.h>
int main(void)
{
int scores[5] = {90, 80, 75, 88, 100};
for (int i = 0; i < 5; i++) {
printf("%d ", scores[i]);
}
return 0;
}字符数组
char text[] = "hello";
printf("%s\n", text);最佳代码实践
- C++ 中固定长度数据优先考虑
std::array,动态长度数据优先考虑std::vector。 - 字符串优先使用
std::string,除非正在学习 C 风格字符串或需要和 C 接口交互。 - 使用 C 风格数组时要明确数组长度,遍历时使用
< 长度,不要写成<= 长度。 - 数组作为函数参数时,同时传入长度。
void print_array(const int arr[], int length)
{
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
}错误用法
int arr[3] = {1, 2, 3};
printf("%d\n", arr[3]); // 错误:越界访问,合法下标是 0、1、2int n = 0;
std::cin >> n;
int arr[n]; // C++ 标准不支持变长数组注意事项
- C99 支持变长数组 VLA,但 C++ 标准不支持。写 C++ 时用
std::vector。 - 数组越界通常不会立刻报错,但可能破坏其他内存,是 C/C++ 常见危险来源;机制细节见 未定义行为。
学习路径
- 上一节:CandCpp流程控制
- 当前阶段:CandCPP基础
- 下一节:CandCpp函数