【问题标题】:can't perform a for loop with iteration in c++无法在 C++ 中执行带有迭代的 for 循环
【发布时间】:2012-04-03 10:16:25
【问题描述】:

我正在开发一个游戏库,我可以在其中添加或删除我的游戏。 到目前为止,我只是列出了 3 款标准游戏,但当我试图对其进行测试时。它给了我一个错误。

我正在尝试对我的向量进行迭代,但由于某种原因它不起作用。我找不到那个原因。

这是我的代码:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{

vector<int>::const_iterator iter;

vector<string> games;
games.push_back("Crysis 2");
games.push_back("God of War 3");
games.push_back("FIFA 12");

cout <<"Welcome to your Games Library.\n";
cout <<"These are your games:\n";
for (iter = games.begin(); iter != games.end(); ++iter)
{
    cout <<*iter <<endl;
}

return 0;

}

【问题讨论】:

  • 也许您应该说出实际错误是什么,而不是让人们猜测。很好,你包含了完整的代码。

标签: c++ visual-studio-2010 vector iteration


【解决方案1】:

你的迭代器和你的 vetcor 的类型不兼容。

使用:

vector<string>::const_iterator iter;

为了让事情变得更简单,typedef 你的集合类型可能会更好:

typedef std::vector<std::string> GamesListType;
GamesListType::const_iterator iter;
GamesListType games;

【讨论】:

  • 我简直不敢相信我没有看到。感谢您提供其他信息!
【解决方案2】:

您的迭代器与容器类型不匹配:这样声明

vector<string>::const_iterator iter;

【讨论】:

  • 当然!!我现在觉得自己好傻。感谢您在我的愚蠢帖子上的回答:)
【解决方案3】:

您正在尝试使用 int 常量迭代器迭代 string 向量。更改您的迭代器类型。

【讨论】:

  • 没关系。我投票结束这个,所以没有更多的答案被发布。你最好接受一个答案。
猜你喜欢
  • 2020-08-02
  • 2021-04-13
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
  • 2012-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多