c++中的STL映射错误C2679

STL Map error C2679 in C++

本文关键字:错误 C2679 映射 STL 中的 c++      更新时间:2023-10-16

当我尝试打印成对的int &STL Map中的字符串:

这是我使用的代码:

#include <iostream>
#include <utility>
#include <map>
using namespace std;
typedef map<int,string> intID;
int main(){
    intID ID;
    ID.insert(pair<int,string>(123,"studentname1"));
    ID.insert(pair<int,string>(124,"studentname2"));
    ID.insert(pair<int,string>(122,"studentname3"));
    intID::iterator IDIter;
    for(IDIter = ID.begin();IDIter != ID.end();++IDIter){
        cout <<"ID: " << IDIter->first <<", Name: " << IDIter->second << endl;
    }
}

错误发生在", Name: " << IDIter->second部分,<<下划线表示"没有操作符匹配这些操作数"

编译错误是:

错误1错误C2679:二进制'<<':没有找到带a的操作符'std::string'类型的右操作数(否则不接受)转换)

我试图打印出这对中的第二个成员(studentname)我是STL映射的新手,所以我不确定我做错了什么,我需要改变什么?

您需要包含<string>标头。您只能通过偶然包含其他头文件来使用std::string类型。你不能依赖这个。包括<string>也会带来operator<<的重载,允许您输出字符串。

相关文章: