数组

数组简介

数组是存储在连续内存位置的相同数据类型的元素集合。它们通过索引提供常数时间的元素访问。

数组声明和初始化

数组可以通过多种方式声明和初始化:

数组声明

#include <iostream>
using namespace std;

int main() {
    // Method 1: Declaration with size
    int numbers[5];
    
    // Method 2: Declaration with initialization
    int scores[5] = {95, 87, 92, 78, 85};
    
    // Method 3: Let compiler determine size
    int grades[] = {90, 88, 95, 92, 87};
    
    // Method 4: Partial initialization (remaining elements are 0)
    int values[10] = {1, 2, 3};  // Only first 3 elements initialized
    
    // Method 5: Initialize all elements to 0
    int zeros[5] = {0};  // All elements become 0
    
    // Print scores array
    cout << "Scores: ";
    for (int i = 0; i < 5; i++) {
        cout << scores[i] << " ";
    }
    cout << endl;
    
    // Print size of grades array
    cout << "Size of grades array: " << sizeof(grades)/sizeof(grades[0]) << endl;
    
    return 0;
}

数组操作

常见的数组操作包括访问、修改和遍历元素:

数组操作

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int size = 5;
    
    // Accessing elements
    cout << "First element: " << arr[0] << endl;
    cout << "Last element: " << arr[size-1] << endl;
    
    // Modifying elements
    arr[2] = 35;  // Change third element
    cout << "Modified third element: " << arr[2] << endl;
    
    // Iterating through array
    cout << "All elements: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // Range-based for loop (C++11)
    cout << "Using range-based for: ";
    for (int element : arr) {
        cout << element << " ";
    }
    cout << endl;
    
    return 0;
}

多维数组

C++ 支持多维数组,通常用于矩阵和表格:

二维数组示例

#include <iostream>
using namespace std;

int main() {
    // 2D array declaration and initialization
    int matrix[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
    
    int rows = 3, cols = 4;
    
    // Print the matrix
    cout << "Matrix:" << endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
    
    // Access specific element
    cout << "Element at (1,2): " << matrix[1][2] << endl;
    
    // Modify element
    matrix[0][0] = 100;
    cout << "Modified element at (0,0): " << matrix[0][0] << endl;
    
    // Sum of all elements
    int sum = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            sum += matrix[i][j];
        }
    }
    cout << "Sum of all elements: " << sum << endl;
    
    return 0;
}

数组算法

数组上常见的算法包括搜索、排序和寻找极值:

数组算法

#include <iostream>
#include <climits>
using namespace std;

// Linear search
int linearSearch(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i;  // Return index if found
        }
    }
    return -1;  // Return -1 if not found
}

// Find maximum element
int findMax(int arr[], int size) {
    int max = INT_MIN;
    for (int i = 0; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

// Reverse array
void reverseArray(int arr[], int size) {
    int start = 0, end = size - 1;
    while (start < end) {
        swap(arr[start], arr[end]);
        start++;
        end--;
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int size = sizeof(arr)/sizeof(arr[0]);
    
    cout << "Original array: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // Linear search
    int target = 25;
    int index = linearSearch(arr, size, target);
    if (index != -1) {
        cout << "Element " << target << " found at index: " << index << endl;
    } else {
        cout << "Element " << target << " not found" << endl;
    }
    
    // Find maximum
    int max = findMax(arr, size);
    cout << "Maximum element: " << max << endl;
    
    // Reverse array
    reverseArray(arr, size);
    cout << "Reversed array: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    return 0;
}

数组与其他数据结构对比

操作 数组 向量 链表
索引访问 O(1) O(1) O(n)
开头插入 O(n) O(n) O(1)
末尾插入 O(1) O(1) amortized O(n)
删除元素 O(n) O(n) O(1)
内存开销

最佳实践

  • 始终检查数组边界以避免缓冲区溢出
  • 初始化数组以避免垃圾值
  • 对不应修改的数组使用 const
  • 考虑使用 std::array 或 std::vector 获得更好的安全性
  • 为数组索引使用有意义的变量名