阅读量:81
在C++中,您可以使用索引来访问和修改数组的元素
#include
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 class="hljs-string">" ";
}
std::cout<< std class="hljs-comment">// 修改数组中的第3个元素(索引为2)
int index_to_modify = 2;
int new_value = 99;
if (index_to_modify >= 0 && index_to_modify < n xss=removed class="hljs-keyword">else {
std::cout << "索引超出范围"<< std class="hljs-comment">// 输出修改后的数组
std::cout << "修改后的数组: ";
for (int i = 0; i < n class="hljs-string">" ";
}
std::cout<< std class="hljs-keyword">return 0;
}
在这个示例中,我们首先定义了一个包含5个整数的数组。然后,我们修改了索引为2的元素(即第三个元素),将其值更改为99。最后,我们输出了修改后的数组。注意,数组的索引是从0开始的,因此索引2实际上是数组中的第三个元素。