Possible Duplicate:
Why isn't the [] operator const for STL maps?
I've boiled this down to (what I think is) its simplest form:
#include <iostream>
#include <map>
#include <vector>
class NumberHolder
{
public:
NumberHolder( const std::string aKey, const double aNumber );
void printSmallestMappedNumber( const unsigned int theIndex ) const;
private:
std::vector< std::map< std::string, double> > theNamedNumberMapVector;
};
NumberHolder::NumberHolder( const std::string key, const double aNumber )
{
std::map<std::string, double> aTempMap;
aTempMap[key] = aNumber;
theNamedNumberMapVector.push_back(aTempMap);
}
void NumberHolder::printSmallestMappedNumber( const unsigned int theIndex ) const
{
std::map<std::string, double>& aSpecificMap = theNamedNumberMapVector[theIndex];
std::cout << aSpecificMap["min"] << std::endl;
}
int main(int argc, char* argv[])
{
NumberHolder aTaggedNumberHolder("min", 13);
aTaggedNumberHolder.printSmallestMappedNumber( 0 );
return 0;
}
I have a vector full of maps, and each map is full of (string) "tagged" numbers. I'm trying to keep as tight of control over access to the visibility/mutability of the variables involved.
Anyhow, the compiler fails with this error
Binding of reference to type 'std::map' to a value of type 'const std::map, double, std::less >, std::allocator, double> > >' drops qualifiers
My first (underbaked) attempt was making the map const..., as I'm not modifying the map, only retrieving a value from it:
const std::map<std::string, double>& aSpecificMap = theNamedNumberMapVector[theIndex];
Which then presents me with this admittedly shorter, but actually a bit more confusering error:
No viable overloaded operator[] for type 'const std::map<std::string, double>'
On the following line instead:
std::cout << aSpecificMap["min"] << std::endl;
However, perhaps because I've been trying to untangle this for a bit, my solution seems to be awfully, awfully crufty:
std::map<std::string, double>& aSpecificMap = const_cast<std::map<std::string, double>&>(theNamedNumberMapVector[theIndex]);
const_casting away the [const derp] qualifier works around my problem, but I would really like to have a clear understanding of exactly what's going on. I'm guessing that the compiler is disgruntled about my access to the map (in my second attempt, above) and believes that I will use & abuse my access to the map's contents. I'd really like / need to be able to explain stuff like this to other people, as well as trying not to abuse the language and ultimately end up on The Daily WTF, because, you know, shame and stuff.