【问题标题】:Unable to use Iterator for a MAP to PRINT STRING. (able to print int)无法将迭代器用于 MAP 以打印字符串。 (能够打印int)
【发布时间】:2023-03-07 02:17:01
【问题描述】:

我尝试使用迭代器在 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。我无法打印字符串。请提出解决方案。

【问题讨论】:

  • 当您已经在使用using namespace std 时,我不明白您为什么在任何地方都重复使用std::

标签: string visual-c++ iterator cout


【解决方案1】:

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

只需使用cout&lt;&lt; it-&gt;second&lt;&lt;endl;

所有错误都会自动解决。

附:请参阅我对您的问题的评论。

【讨论】:

    猜你喜欢
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    相关资源
    最近更新 更多