【问题标题】:STL Map error C2679 in C++C++ 中的 STL 映射错误 C2679
【发布时间】:2013-04-30 06:30:54
【问题描述】:

我在尝试在 STL 映射中打印成对的 int 和字符串时遇到问题:

这是我正在使用的代码:

#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: " &lt;&lt; IDIter-&gt;second 部分,&lt;&lt; 下划线表示“没有运算符与这些操作数匹配”

编译错误是:

错误 1 ​​错误 C2679: 二进制 '

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

【问题讨论】:

    标签: c++ stl containers


    【解决方案1】:

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

    【讨论】:

    • 我认为您还应该包括&lt;ostream&gt;,因为&lt;iostream&gt; 只定义了std::cout,而不是它的成员。但是,当一个实现有用地在 &lt;iostream&gt; 中包含 &lt;ostream&gt; 时,您通常会侥幸逃脱。
    • @MSalters operator&lt;&lt;std::string 重载不在 I/O 库中,而是在字符串库中。
    • 是的。但我写了“also include ostream”,因为上次使用的重载 (&lt;&lt; std::endl) 需要它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多