2017-10-19 157 views
-2

我已经安装了CodeBloks,并且正在用一个简单的问题对它进行测试。无法打印指向unordered_map元素的指针

#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>&&' 
+2

这不是错误消息[你得到(https://ideone.com/Fc4Dc1): “_error:'operator <<''不匹配(操作数类型是'std :: ostream' {aka'std :: basic_ostream '}'和''std :: pair '' _“而且,std :: pair没有这样的操作符重载 –

+1

当读取错误信息时,从顶部开始,而不是从底部开始,特别是对于这样的错误,其中有一个错误输出很多* – Kevin

回答

2

cppreference

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

的地图(无序或不)采取由key的,和value。您可以通过迭代器中的firstsecond来访问它。

+1

非常感谢你,我现在很抱歉打扰你这个问题。 – Oana

1

错误可能是误导。实际的问题是无序映射会以成对的键和值进行迭代,并且没有直接打印这些对的运算符<<

可以通过it->second访问通过it->first和密钥值:

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

Demo.

0

的地图存储键/值对,并it提供构件first(代表键)和一个会员second(代表价值)。请尝试以下cout...语句来:

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

结构绑定将很好地工作,为此:

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