我如何使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP