繁体   English   中英

C++ | 重载运算符 << | 标准::map

[英]C++ | overload operator << | std::map

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

不存在从“std::_Rb_tree_const_iterator<std::pair<const int, int>>”到“std::_Rb_tree_iterator<std::pair<const int, int>>”的合适的用户定义转换

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;
}

如何正确获取对 map 迭代器的引用? 我只能使用 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 map,因此begin返回一个const_iterator ,而不是一个iterator 没有定义operator<<接受stringstream作为第二个参数,因此使用它的成员 function 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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM