阅读量:142
在C++中,可以使用以下方法来有效初始化string数组:
- 使用循环逐个初始化每个元素:
#include
#include
int main() {
const int SIZE = 5;
std::string arr[SIZE];
for (int i = 0; i < SIZE xss=removed class="hljs-string">"Element" + std::to_string(i);
}
for (int i = 0; i < SIZE class="hljs-keyword">return 0;
}
- 使用初始化列表来初始化数组元素:
#include
#include
int main() {
const int SIZE = 5;
std::string arr[SIZE] = {"Element0", "Element1", "Element2", "Element3", "Element4"};
for (int i = 0; i < SIZE class="hljs-keyword">return 0;
}
这两种方法都可以有效地初始化string数组,具体选择哪种方法取决于初始化的复杂程度和个人喜好。