如何解决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();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。