在遍历此向量时我没有得到正确的输出,我不确定为什么
vector<string> words = {"once","i","was","seven"};
for(int i=0;i<=words.size();i++){
cout<<words[i]<<endl;
for(int j =0; j<=words.size();j++){
cout<<words[j]<<endl;
}
}
此代码应打印:once once i was seven i once i was seven was once i was seven seven once i was seven
,但它打印:once once i was seven
,我该如何解决
答案 0 :(得分:1)
打印“一次,我7岁”后,由于单词size为4,并且您正在循环5个元素(从i = 0到4,而word [4]将是未定义的行为),它将崩溃。只需从条件中删除等号,您就可以开始了。
vector<string> words = {"once","i","was","seven"};
for(int i = 0; i < words.size(); i++){
cout << words[i] << endl;
for(int j = 0; j < words.size(); j++){
cout << words[j] << endl;
}
}
答案 1 :(得分:1)
vector<string> words = {"once","i","was","seven"};
words[0] == "once"
words[1] == "i"
words[2] == "was"
words[3] == "seven"
<= words.size()
使循环带您进入
words[4] == <undefined behaviour>
因此,最大索引为size()-1
。您通常可以通过使用基于范围的for循环来避免麻烦:
for(const auto& outer_word : words) {
cout<< outer_word << endl;
for(const auto& word : words) {
cout << word << "\n";
}
}