【问题标题】:C++: Iterate Through MapC++:遍历地图
【发布时间】:2014-02-06 01:43:43
【问题描述】:

我正在尝试遍历地图以读取字符串,然后将向量中的所有数字读取到文件中。我复制并粘贴了 typedef 行,然后将其调整为我的代码,所以我不肯定它是正确的。无论如何,Visual Studio 在我的循环中使用 iterator_variable 时给了我错误。它说类型名称是不允许的。我该如何解决这个问题?

ofstream output("output.txt");
typedef map<string, vector<int>>::iterator iterator_variable;
for (iterator_variable iterator = misspelled_words.begin(); iterator != misspelled_words.end(); iterator++)
{
    output << iterator_variable->first;
    for (int i = 0; i < misspelled_words.size(); i++)
    {
        output << " " << iterator_variable->second[i];
    }
    output << endl;
}

【问题讨论】:

  • 正如错误所说,iterator_variable 是一种类型,请将其替换为 for 正文中的变量名称 iterator。内部for 也很可疑。确定要循环遍历 [0, misspelled_words.size()] 而不是 [0, iterator-&gt;second.size())?

标签: c++ visual-studio c++11


【解决方案1】:

您应该像 iterator-&gt;first 一样访问迭代器,而不是 iterator_variable-&gt;first。

对于内部循环,您可能希望从 0 迭代到 iterator-&gt;second.size() 而不是 misspelled_words.size()。

ofstream output("output.txt");
typedef map<string, vector<int>>::iterator iterator_variable;
for (iterator_variable iterator = misspelled_words.begin(); iterator != misspelled_words.end(); iterator++)
{
    output << iterator->first;
    for (int i = 0; i < iterator->second.size(); i++)
    {
        output << " " << iterator->second[i];
    }
    output << endl;
}

【讨论】:

    【解决方案2】:

    您也可以使用基于 for 循环和 auto 的新范围来获得更简洁易读的代码。

    ofstream output("output.txt");
    for ( auto const & ref: misspelled_words ) {
        output << ref.first;
        for (auto const & ref2 : ref.second ) {
            output << " " << ref2;
        }
        output << "\n"; // endl force a stream flush and slow down things.
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-04
      • 2011-03-23
      • 2011-06-18
      • 2020-10-23
      • 2011-12-22
      相关资源
      最近更新 更多