数组是一种基本的数据结构,用于按顺序存储元素的集合。但是元素可以随机存取,因为数组中的每个元素都可以通过数组索引来识别。
数组可以有一个或多个维度。这里我们从一维数组开始,它也被称为线性数组。这里有一个例子:
A | 6 | 3 | 8 | 7 | 2 | 9 |
---|---|---|---|---|---|---|
index | 0 | 1 | 2 | 3 | 4 | 5 |
在上面的例子中,数组 A 中有 6 个元素。也就是说,A 的长度是 6 。我们可以使用 A[0] 来表示数组中的第一个元素。因此,A[0] = 6 。类似地,A[1] = 3,A[2] = 8,依此类推。
数组中的操作
让我们来看看数组的用法:
c++代码
#include <iostream>
using namespace std;
int main() {
// 1. Initialize
int a0[5];
int a1[5] = {1, 2, 3}; // other element will be set as the default value
// 2. Get Length
int size = sizeof(a1) / sizeof(*a1);
cout << "The size of a1 is: " << size << endl;
// 3. Access Element
cout << "The first element is: " << a1[0] << endl;
// 4. Iterate all Elements
cout << "[Version 1] The contents of a1 are:";
for (int i = 0; i < size; ++i) {
cout << " " << a1[i];
}
cout << endl;
cout << "[Version 2] The contents of a1 are:";
for (int& item: a1) {
cout << " " << item;
}
cout << endl;
// 5. Modify Element
a1[0] = 4;
// 6. Sort
sort(a1, a1 + size);
}
java代码:
// "static void main" must be defined in a public class.
public class Main {
public static void main(String[] args) {
// 1. Initialize
int[] a0 = new int[5];
int[] a1 = {1, 2, 3};
// 2. Get Length
System.out.println("The size of a1 is: " + a1.length);
// 3. Access Element
System.out.println("The first element is: " + a1[0]);
// 4. Iterate all Elements
System.out.print("[Version 1] The contents of a1 are:");
for (int i = 0; i < a1.length; ++i) {
System.out.print(" " + a1[i]);
}
System.out.println();
System.out.print("[Version 2] The contents of a1 are:");
for (int item: a1) {
System.out.print(" " + item);
}
System.out.println();
// 5. Modify Element
a1[0] = 4;
// 6. Sort
Arrays.sort(a1);
}
}