简体   繁体   English

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

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

I'm trying to overload operator << of a map within a struct, but getting a compilation error:我试图在结构中重载 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不存在从“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;
}

How do I correctly get a reference to the iterator of the map?如何正确获取对 map 迭代器的引用? I can only use C++ 98.我只能使用 C++ 98。

This is my complete code这是我的完整代码

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

You have a const map, hence begin returns a const_iterator , not an iterator .你有一个const map,因此begin返回一个const_iterator ,而不是一个iterator There is no defined operator<< to accept stringstream as a second argument, hence use its member function str , as follows没有定义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