C++ |重载运算符 << | std::map

C++ | overload operator << | std::map

我试图在结构中重载映射的运算符 <<,但出现编译错误:

no suitable user-defined conversion from "std::_Rb_tree_const_iterator<std::pair<const int, int>>" to "std::_Rb_tree_iterator<std::pair<const int, int>>" exists

ostream& operator<<(ostream& os, const map<int, int>& neighbors)
{
    string res;
    map<int, int>::iterator it = neighbors.begin();
    stringstream ss;

    while (it != neighbors.end())
    {
        ss << "[id: " << it->first << " cost: " << it->second << "] ";
        it++;
    }
    return os << ss;
}

如何正确获取对地图迭代器的引用?我只能使用 C++ 98.

这是我的完整代码

#pragma once

#include <map>
#include <string>
#include <sstream>

using namespace std;

struct LSA
{
    int id;
    int seqNum;
    map <int, int> neighbors;

    friend ostream& operator<<(ostream& os, const LSA& lsa);
    friend ostream& operator<<(ostream& os, const map<int, int>& neighbors);
};

ostream& operator<<(ostream& os, const LSA& lsa)
{
    return os << "[id: " << lsa.id << " seqNum: " << lsa.seqNum << " (" << lsa.neighbors.size() << " neighbors)";
}

ostream& operator<<(ostream& os, const map<int, int>& neighbors)
{
    string res;
    map<int, int>::iterator it = neighbors.begin();
    stringstream ss;

    while (it != neighbors.end())
    {
        ss << "[id: " << it->first << " cost: " << it->second << "] ";
        it++;
    }
    return os << ss;
}

您有一张 const 地图,因此 begin returns 一张 const_iterator,而不是一张 iterator。没有定义operator<<接受stringstream作为第二个参数,因此使用它的成员函数str,如下

ostream& operator<<(ostream& os, const map<int, int>& neighbors)
{
    string res;
    map<int, int>::const_iterator it = neighbors.cbegin();
    stringstream ss;

    while (it != neighbors.end())
    {
        ss << "[id: " << it->first << " cost: " << it->second << "] ";
        it++;
    }
    return os << ss.str();
}