【问题标题】:Unable to print vector values from map in maps无法在地图中打印地图中的矢量值
【发布时间】:2021-04-07 18:36:28
【问题描述】:

我正在尝试打印地图地图的全部内容,但一直遇到问题。 这是我的地图初始化map<int, map<int, vector<int>>> myMap;

我已经尝试了以下代码:

for( auto const & cit : myMap)
    {
        cout << cit.first << " : ";
        auto const & imap = cit.second;
        for( auto const & cit2 : imap )
        {
            cout << cit2.first << ":" << cit2.second << ","; // errors out
            //cout << cit2.first << ":"; // works, but it is not printing out the vector<int> portion
        }
        cout << endl;
    }

如上所述,一旦使用cit2.second,我就会收到以下错误: error: no match for 'operator&lt;&lt;' (operand types are 'std::basic_ostream&lt;char&gt;' and 'const std::vector&lt;int&gt;')|

有人可以给我一些见解吗?

【问题讨论】:

  • 您需要再次循环 cit2.secondcout 您的矢量元素
  • 错误'operator&lt;&lt;' (operand types are 'std::basic_ostream&lt;char&gt;' and 'const std::vector&lt;int&gt;')有什么不清楚的地方?没有为流定义 operator&lt;&lt;std::vector&lt;int&gt;。您要么需要自己定义它,要么通过循环打印std::vector&lt;int&gt; 的内容。
  • 假设您不理解错误消息是否正确?这就是您要了解的内容吗?

标签: c++ dictionary


【解决方案1】:

你需要这样做。

for( auto const & cit : myMap)
    {
        cout << cit.first << " : ";
        auto const & imap = cit.second;
        for( auto const & cit2 : imap )
        {
            cout << cit2.first << ":";
            auto const &vec = cit2.second;
            for(auto const &i : vec)
            {
                cout<<i<<" ";
            }cout<<endl;   
            //cout << cit2.first << ":"; // works, but it is not printing out the vector<int> portion
        }
        cout << endl;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 2016-01-29
    • 2021-07-24
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多