c++stliteratoroperator-overloadingconst-iterator

C++ | overload operator << | std::map


I'm trying to overload operator << of a map within a struct, but getting a compilation error:

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

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? I can only use 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;
}

Solution

  • You have a const map, hence begin returns a const_iterator, not an iterator. There is no defined operator<< to accept stringstream as a second argument, hence use its member function str, as follows

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