In my header file I have included the std::map and use the appropriate namespace.
One of my members is:
map<unsigned int, double> pT_Spam;
And in my .cpp file I attempt to do something that I have been doing frequently for some time now:
for(map<unsigned int, double>::iterator it=pT_Spam.begin() ; it!=pT_Spam.end() ; it++) {/*code*/}
The above is even mentioned in one the examples of using std::map at cplusplus.com . Even though I have done pretty much the same in other parts of the code which cause no compile errors, on this particular line I get the following error from Cygwin:
error: conversion from `std::_Rb_tree_const_iterator<std::pair<const unsigned int, double> >' to non-scalar type `std::_Rb_tree_iterator<std::pair<const unsigned int, double> >' requested
Which seems rather strange. Any idea what might be wrong? (my header is, of course, included in my .cpp)
It would seem that at the scope this loop exists, the map is const. For example, is the loop in a class method declared const, like so?
or passed as a const argument, like this?
If it is, you must use const iterators:
Or, if you’re using C++11, then you should use the auto keyword:
Since in the case you’ve shown you must use const iterators, you can’t use them to modify the map or the data within it. That’s const correctness, and it’s a good thing :).