【问题标题】:Iterating through vectors遍历向量
【发布时间】:2013-07-14 15:26:57
【问题描述】:

我正在尝试将文本文件中的字符串值添加到向量中。在这样做的同时,我还在检查字符串中的字符数,然后当到达具有所需字符数的单词时,我将该字符串添加到向量中。

但是当我调试我的程序时,我一直看到越界异常,它打印出的字符串比所需的字符数多。

vector<string> words;
vector<string> chosenWords;
ifstream in("WordDatabase.txt");

while(in) {
  string word;
  in >> word;
  cout << word << endl;
  //push in selected words based on num of chars
  words.push_back(word);
}

for(vector<string>::iterator itr=words.begin(); itr!=words.end();++itr)
{
    if((*itr).length() >= 2 || (*itr).length() <= 7)
    {
        cout << (*itr) << endl;
        chosenWords.push_back(*itr);
    }
}

【问题讨论】:

  • 越界错误对应哪一行?
  • 长度为 2+ 或 7- 这听起来很奇怪。确定你说的不是 && 吗?
  • 该死的。你在 2 分钟内解决了它,而我花了 2-3 小时思考它。谢谢博格!
  • @KerrekSB 哈你什么意思?

标签: c++ vector iterator text-files


【解决方案1】:

长度为 2+ 或 7- 听起来很奇怪。您的条件很可能应该是:

if((*itr).length() >= 2 && (*itr).length() <= 7)

作为旁注,你最好阅读这样的词:

string word;
while(in >> word) {
  cout << word << endl;
  //push in selected words based on num of chars
  words.push_back(word);
}

【讨论】:

  • 有什么区别?对不起,如果我听起来很菜,因为我 2-3 周前才开始使用 c++。
  • 我相信这个版本涵盖了您的版本没有的边缘情况。我必须挖掘才能找到具体的答案,但如果你漫游得足够多,你会发现这是规范的做事方式。
  • @JoelSeah:您的while (in) 循环错误,原因与while (!in.eof()) 错误的原因相同。见:Why is iostream::eof inside a loop condition considered wrong?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 2021-11-23
  • 2015-10-07
相关资源
最近更新 更多