簡體   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