#c #stl #iterator #operator-overloading #const-iterator
#c #stl #итератор #оператор-перегрузка #const-итератор
Вопрос:
Я пытаюсь перегрузить operator << карты внутри структуры, но получаю ошибку компиляции:
не существует подходящего пользовательского преобразования из «std::_Rb_tree_const_iterator<std::pair<const int, int>>» в «std::_Rb_tree_iterator<std::pair<const int, int>>»
ostreamamp; operator<<(ostreamamp; os, const map<int, int>amp; 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 ostreamamp; operator<<(ostreamamp; os, const LSAamp; lsa);
friend ostreamamp; operator<<(ostreamamp; os, const map<int, int>amp; neighbors);
};
ostreamamp; operator<<(ostreamamp; os, const LSAamp; lsa)
{
return os << "[id: " << lsa.id << " seqNum: " << lsa.seqNum << " (" << lsa.neighbors.size() << " neighbors)";
}
ostreamamp; operator<<(ostreamamp; os, const map<int, int>amp; 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;
}
Комментарии:
1. Попробуйте использовать
map<int, int>::const_iterator
Ответ №1:
У вас есть const
карта, следовательно begin
, возвращает a const_iterator
, а не an iterator
. В operator<<
stringstream
качестве второго аргумента не определено, поэтому используйте его функцию str
-член следующим образом
ostreamamp; operator<<(ostreamamp; os, const map<int, int>amp; 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();
}