简体   繁体   中英

C++ map iterator issue

I have a weird error in the following code :

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

As you can see, it's nothing out of the ordinary, it's a simple code that calculates the average marks in a map. I tested this in an online compiler and it worked, but when I try to compile it on my machine (I'm using CodeBlocks with the GNU GCC Compiler) I get this error:

error: conversion from 'std::map, float>::const_iterator {aka std::_Rb_tree_const_iterator, float> >}' to non-scalar type 'std::map, float>::iterator {aka std::_Rb_tree_iterator, float> >}' requested|

You have a const function that is trying to iterate what I assume is a member variable (marks). Make sure you use a const iterator:

for(map<string, float>::const_iterator iter = marks.begin();

The other answer shows how to fix the error, but here's another way to calculate the average using std::accumulate . Using this method, you don't need to worry about iterator types and such, and the loop can be eliminated as well.

float Student::getAverageMark() const throw (NoMarkException)
{
    if(marks.empty()) {
        return 0;
    }
    return std::accumulate(marks.begin(), marks.end(), 0.0f,
                           [](float acc, decltype(marks)::value_type const& elem) {
                              return acc + elem.second;
                           }) / marks.size();
}

Also, exception specifications have been deprecated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM