【问题标题】:Print C++ Map by iteration通过迭代打印 C++ Map
【发布时间】:2013-07-02 23:29:07
【问题描述】:

有没有更简单的方法来解决这个问题,或者我做错了什么?我认为我的问题的核心在代码中,

vector<int> &v = miss_words[*i];

但也许我只是把整个概念弄错了。有什么建议吗?

代码:

void print_map(map<string, vector<int> > miss_words)    // Prints out dictionary set
{
    map<string, vector<int> >::iterator it = miss_words.begin();    // Creates an iterator
    while(it != miss_words.end())           // While hasn't reached the end
    {
        vector<int> &v = miss_words[*it];   // Accesses Vector in map
        for(unsigned int g = 0; g <= v.size(); g++)
        {
            cout<<v.at(g)<<": ";            
            cout<<v.at(g)<<" "<<endl;   // Print out data at i
        }
        it++;                   // Increment iterator
    }
}

编译器会说“在miss_words中没有'operator[]'的匹配项。

【问题讨论】:

  • &lt;= 非常可疑。
  • 你的权利...稍后抛出错误...感谢您的帮助! @KerrekSB

标签: c++ maps iteration


【解决方案1】:

你想说vector&lt;int&gt; &amp;v = it-&gt;second;

迭代器的值类型是map的值类型,即pair&lt;string, vector&lt;int&gt;&gt;


事实上,在现代 C++ 中,您可以这样写更简单,更不容易出错,如下所示:

for (auto const & p : miss_words)
{ 
    for (auto const & x : p.second)
    {
        cout << x << ": " << x << " \n";
    }
}

这样,您甚至不必担心矢量的大小。

【讨论】:

  • 谢谢!我不知道“第二个”符号
  • @wawiti:我很高兴它有帮助,但请注意它不是“符号”。 second 只是 pair 类型的成员...
猜你喜欢
  • 2021-09-14
  • 2015-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多