Closed. This question is not reproducible or was caused by typos。它当前不接受答案。












想改善这个问题吗?更新问题,以便将其作为on-topic用于堆栈溢出。

去年关闭。



Improve this question




遍历此 vector 时,我没有得到正确的输出,我不确定为什么
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,我该如何解决它

最佳答案

在打印“一次我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;
    }
}

关于c++ - 通过 vector 循环时如何获得正确的输出? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55886654/

10-10 10:34