无法将迭代器用于 MAP 以打印字符串.(能够打印 int)



我尝试使用迭代器在MAP中打印字符串,但出现错误。

程序-

#include<iostream>
#include<stdio.h>
#include<conio.h>
#include<map>
#include<string.h>
#include<unordered_map>
using namespace std;
void main()
{
std::map<int,std::string>mymap;
std::map<int,std::string>::iterator it;
mymap.insert(make_pair(10, "sid"));
mymap.insert(make_pair( 20, "sam"));
for (it = mymap.begin(); it != mymap.end(); it++)
{
//printf("%s n", it->second);
std::cout <<*it->second << std::endl;
}
system("pause");
_getch;
}

错误列表

1.Error C2679   binary '<<': no operator found which takes a right-hand 
the operand of type 'std:: string' (or there is no acceptable conversion)  
2.Error (active) no operator "<<" matches these operands    

我能够正确打印 int。我无法打印字符串。请提出解决方案。

这不是您访问迭代器指向的对象的方式。

只需使用cout<< it->second<<endl;.

然后自动解决所有错误。

附言请参阅我对你问题的评论。

最新更新