问题描述
我正在尝试在结构中重载地图的运算符
不存在从“ 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();
}