修改元素
本课属于 Coddy C++ 学习旅程的“基础知识”单元。第 60 课,共 74 课。
除了访问数组中的元素,你还可以修改它们。要修改数组中的特定元素,可以使用它的索引为其赋一个新值。
下面是一个示例:
std::string my_array[] = {"apple", "banana", "cherry"};
my_array[1] = "orange";
std::cout << my_array[0] << ", " << my_array[1] << ", " << my_array[2] << std::endl;输出:
apple, orange, cherrybanana 被改成了一个 orange
挑战
简单创建一个程序,使其能够:
- 按以下顺序接收 3 个输入:
n:数组中的元素数量index:索引位置(0 到 n-1)newElement:一个新值(字符串)
- 然后接收 n 个字符串,用来填充数组
- 将索引为
index的元素替换为值newElement,从而修改数组 - 最后打印修改后的数组中的所有元素,每行一个
例如,输入如下:
3
1
hello
apple
banana
cherry输出为:
apple
hello
cherry说明:数组有 3 个元素。我们将索引 1 处的元素(banana)替换为 "hello"。
亲手试试
#include <iostream>
#include <string>
int main() {
int n;
int index;
std::string newElement;
std::cin >> n;
std::cin >> index;
std::cin.ignore();
std::getline(std::cin, newElement);
std::string arr[n];
// 使用 n、index、arr 和 newElement 解决问题
// 你也可以根据需要声明其他变量
for (int i = 0; i < n; i++) {
// 填充 arr
// 读取一个字符串值,并将其存入 arr[i]
}
// 修改 arr
// 将位置 'index' 处的元素设为 'newElement'
// 打印 arr
// 遍历数组并打印每个元素
return 0;
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: C++ 在线编译器