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

问题描述

我正在尝试在结构中重载地图的运算符

不存在从“ std :: _ Rb_tree_const_iterator >”到“ std :: _ Rb_tree_iterator >”的合适的用户定义转换>

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,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,int>::iterator it = neighbors.begin();
    stringstream ss;

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

解决方法

您有一个const映射,因此begin返回一个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();
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...