如何在 C++ 中使用数组?
数组是连续内存位置中相同类型的一系列元素,可以通过向唯一标识符添加索引单独引用这些元素。要在 C++ 中使用数组,首先需要声明它,例如,
int arr[10];
这声明了一个大小为 10 的类型为 int 的数组。它可以在连续内存中存储 10 个整数。要引用其任何元素,你需要使用数组访问运算符并向其提供要访问的元素的索引。C++ 数组的索引从 0 开始。因此,在数组 arr 中,有 10 个元素,索引分别为 0、1、2、...9。要访问第三个元素(即索引为 2 的元素),你可以这样写:arr[2]。
你可以像下面这样在一个循环中访问所有元素:
#include<iostream>
using namespace std;
int main() {
int arr[10];
// Create a loop that starts from 0 and goes to 9
for(int i = 0; i < 10; i++) {
cin >> arr[i]; // Input the ith element
}
// Print the elements you took as input
for(int i = 0; i < 10; i++) {
cout << arr[i] << endl; // Input the ith element
}
}结果
这将给出以下结果:
1 5 -6 45 12 9 -45 12 3 115
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP