【发布时间】:2019-06-07 04:34:57
【问题描述】:
我正在创建一个小字典。我创建了一个字符串向量来预先打印一些单词,以将其中一个作为用户的输入并向他们描述单词。
我尝试在谷歌上搜索并尝试在 for 循环中设置 unsigned int i = 0。
执行此操作的部分代码如下:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> word = {"none", "jump fatigue" , "scrim game", "box up", "turtling", "swing", "flickshot", "tracking", "panic build", "cone jump", "ttv", "one-shot", "tagged", "blue", "white", "lasered", "melted", "default", "bot", "stealth", "aggresive", "sweaty", "tryhard", "choke"};
for(int i = 0; i <= word.size(); i++){
cout<<i<<")"<< word[i] << endl;
}
return 0;
}
它打印时没有任何错误,并且在运行代码结束时它会冻结一段时间并以,
Process terminated with status -1073741819(0 minute(s), 4 second(s))
而它应该以 0 结束
在调试我得到的代码时
warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
【问题讨论】:
-
i <=应该是i <,您的最后一次循环迭代读取到向量的末尾。或者更好的是,使用基于范围的 for 循环来避免这种错误。