在C++中,可以使用以下方法来有效初始化string数组:
#include <iostream>
#include <string>
int main() {
const int SIZE = 5;
std::string arr[SIZE];
for (int i = 0; i < SIZE; i++) {
arr[i] = "Element" + std::to_string(i);
}
for (int i = 0; i < SIZE; i++) {
std::cout << arr[i] << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int main() {
const int SIZE = 5;
std::string arr[SIZE] = {"Element0", "Element1", "Element2", "Element3", "Element4"};
for (int i = 0; i < SIZE; i++) {
std::cout << arr[i] << std::endl;
}
return 0;
}
这两种方法都可以有效地初始化string数组,具体选择哪种方法取决于初始化的复杂程度和个人喜好。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:string数组如何初始化