温馨提示×

如何通过索引修改c++数组元素

c++
小樊
81
2024-09-15 16:52:58
栏目: 编程语言

在C++中,您可以使用索引来访问和修改数组的元素

#include<iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5}; // 定义一个包含5个整数的数组
    int n = sizeof(arr) / sizeof(arr[0]); // 计算数组中元素的个数

    // 输出原始数组
    std::cout << "原始数组: ";
    for (int i = 0; i < n; i++) {
        std::cout<< arr[i] << " ";
    }
    std::cout<< std::endl;

    // 修改数组中的第3个元素(索引为2)
    int index_to_modify = 2;
    int new_value = 99;
    if (index_to_modify >= 0 && index_to_modify < n) {
        arr[index_to_modify] = new_value;
    } else {
        std::cout << "索引超出范围"<< std::endl;
    }

    // 输出修改后的数组
    std::cout << "修改后的数组: ";
    for (int i = 0; i < n; i++) {
        std::cout<< arr[i] << " ";
    }
    std::cout<< std::endl;

    return 0;
}

在这个示例中,我们首先定义了一个包含5个整数的数组。然后,我们修改了索引为2的元素(即第三个元素),将其值更改为99。最后,我们输出了修改后的数组。注意,数组的索引是从0开始的,因此索引2实际上是数组中的第三个元素。

0