[英]How do I declare an iterator for a map with the following template - std::map<std::string, T> my_map?
I have the following class declaration - 我有以下类声明-
template <typename T>
class Polynomial{
std::map<std::string, T> _polynomial_
}
In a member function I declared an iterator for this - 在成员函数中,我为此声明了一个迭代器-
typename std::map<std::string, T>::iterator it= _polynomial_.begin();
The completed member function looks like this - 完成的成员函数如下所示:
template <typename T>
void Polynomial<T>::print(std::ostream& out) const
{
typename std::map<std::string, T>::iterator it= _polynomial_.begin();
std::string term;
while(it != _polynomial_.end()){
term = it->second;
term += it->first;
if(it->first < (T)0){
out << "-" << term;
}
else{
out << "+" << term;
}
term = "";
it++;
}
}
In main, I call the function as follows - 总的来说,我将函数调用如下:
Polynomial <double> p1;
p1.add_term("x0",9.862);
std::cout << p1;
However this does not seem to work and I get errors. 但是,这似乎不起作用,并且出现错误。 GCC complains of a conversion error - GCC抱怨转换错误-
Polynomial.hpp:32:47: error: conversion from \‘std::map, double, std::less >, std::allocator, double> > >::const_iterator {aka std::_Rb_tree_const_iterator, double> >}\’ to non-scalar type \‘std::map, double, std::less >, std::allocator, double> > >::iterator {aka std::_Rb_tree_iterator, double> >}\’ requested typename std::map::iterator it= polynomial .begin(); Polynomial.hpp:32:47:错误:从\\ u2018std :: map,double,std :: less>,std :: allocator,double>>> :: const_iterator {aka std :: _ Rb_tree_const_iterator,double>>} \\ u2019为非标量类型\\ u2018std :: map,double,std :: less>,std :: allocator,double>>> :: iterator {aka std :: _ Rb_tree_iterator,double>>} \\ u2019请求的类型名std ::: map :: iterator it = 多项式 .begin();
Can someone tell me what is the correct declaration of the iterator? 有人可以告诉我迭代器的正确声明是什么吗?
Polynomial<T>::print
is a const
member function, inside which the data member _polynomial_
becomes const
too, that means what _polynomial_.begin()
returns is a const_iterator
, which can't be converted to iterator
implicitly. Polynomial<T>::print
是const
成员函数,在其中数据成员_polynomial_
变为const
,这意味着_polynomial_.begin()
返回的是const_iterator
,不能将其隐式转换为iterator
。 (Note that std::map::begin
is overloaded with const
version and non- const
version, the former returns const_iterator
and the latter returns iterator
.) (请注意, const
版本和非const
版本都重载了std::map::begin
,前者返回const_iterator
,而后者返回iterator
。)
Change the code to 将代码更改为
typename std::map<std::string, T>::const_iterator it = _polynomial_.begin();
// ^^^^^^
or use auto
instead, it would deduce the correct type for you. 或改用auto
,它会为您推断出正确的类型。
auto it = _polynomial_.begin();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.