【问题标题】:cannot print pointer to element of unordered_map无法打印指向 unordered_map 元素的指针
【发布时间】:2017-10-19 20:41:06
【问题描述】:

我已经安装了 CodeBloks,我正在用一个简单的问题对其进行测试。

#include <iostream>
#include <unordered_map>

using namespace std;

int main()
{

    unordered_map<int,int> mp;
    mp[1]=2;
    mp[2]=3;
    for(unordered_map<int,int>::iterator it = mp.begin();it!=mp.end();it++)
        cout<<*it<<" ";
    return 0;
}

我收到此错误:

cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'

【问题讨论】:

  • 这不是错误消息that you get: "error: no match for 'operator&lt;&lt;' (操作数类型是 'std::ostream {aka std::basic_ostream&lt;char&gt;}' 和 '@987654327 @'" 而且,std::pair 没有这样的运算符重载。
  • 读取错误消息时,从顶部开始,而不是从底部开始。特别是对于像这样的错误,其中一个错误有 很多 输出。

标签: c++ iterator unordered-map


【解决方案1】:

取自cppreference

for( const auto& n : u ) {
    std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
}

地图(无序或无序)由keyvalue 组成。您可以使用迭代器中的firstsecond 访问它。

【讨论】:

  • 非常感谢,很抱歉这个问题打扰了您。
【解决方案2】:

该错误可能具有误导性。实际的问题是,无序映射会成对地迭代键值对,并且没有&lt;&lt; 运算符可以直接打印这些对。

你可以通过it-&gt;first获取key,通过it-&gt;second获取value:

for(unordered_map<int,int>::iterator it = mp.begin();it!=mp.end();it++)
    cout<<it->first << " " << it->second << endl;

Demo.

【讨论】:

    【解决方案3】:

    映射存储键/值对,it 提供成员 first(代表键)和成员 second(代表值)。试试下面的cout...-statement:

    cout << it->first << ":" << it->second << " ";
    

    【讨论】:

      【解决方案4】:

      结构化绑定可以很好地解决这个问题:

      for(auto [first, second] : mp) {
          cout << first << '\t' << second << '\n';
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-30
        • 2021-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多