我在以下代码中有一个奇怪的错误:
float Student::getAverageMark() const throw (NoMarkException)
{
int sum = 0;
int count = 0;
for(map<string, float>::iterator iter = marks.begin(); iter != marks.end(); ++iter) {
sum += iter->second;
count++;
}
return sum/count;
}
正如您所看到的,它没有什么不同寻常的,它是一个计算 Map 中平均标记的简单代码 . 我在一个在线编译器中对它进行了测试并且它有效,但是当我尝试在我的机器上编译它时(我正在使用带有GNU GCC编译器的CodeBlocks)我收到此错误:
错误:从'std :: map,float> :: const_iterator {aka std :: _ Rb_tree_const_iterator,float >>}'转换为非标量类型'std :: map,float> :: iterator {aka std :: _ Rb_tree_iterator ,float >>>''request |
2 回答
你有一个const函数试图迭代我假设的成员变量(标记) . 确保使用const迭代器:
other answer显示了如何修复错误,但这是使用std::accumulate计算平均值的另一种方法 . 使用此方法,您无需担心迭代器类型等,也可以消除循环 .
此外,exception specifications已被弃用 .