C++ 我真的很想绕着一个';常数';地图问题

C++ 我真的很想绕着一个';常数';地图问题,c++,dictionary,operator-overloading,constants,C++,Dictionary,Operator Overloading,Constants,可能重复: 我把它归结为(我认为是)最简单的形式: #include <iostream> #include <map> #include <vector> class NumberHolder { public: NumberHolder( const std::string aKey, const double aNumber ); void printSmallestMappedNumber( const unsigned in

可能重复:

我把它归结为(我认为是)最简单的形式:

#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;
}
#包括
#包括
#包括
类号持有者
{   
公众:
NumberHolder(const std::string aKey,const double aNumber);
void print smallestmappedNumber(常量unsigned int theIndex)常量;
私人:
std::vector>theNamedNumberMapVector;
};
NumberHolder::NumberHolder(常数std::字符串键,常数双数)
{
std::map-aTempMap;
aTempMap[键]=一个数;
名称数字映射向量。向后推(aTempMap);
}
void NumberHolder::printSmallestMappedNumber(常量unsigned int theIndex)常量
{
std::map&aSpecificMap=namednumbermapVector[theIndex];
std::cout,std::分配器,双>>>'删除限定符

我的第一次(欠烘焙)尝试是使映射为常量…,因为我没有修改映射,只是从中检索一个值:

const std::map<std::string, double>& aSpecificMap = theNamedNumberMapVector[theIndex];
const std::map&aSpecificMap=namednumbermapVector[theIndex];
这就给了我一个公认的较短,但实际上更令人困惑的错误:

No viable overloaded operator[] for type 'const std::map<std::string, double>'
类型“const std::map”没有可行的重载运算符[]
改为在下一行:

 std::cout << aSpecificMap["min"] << std::endl;
std::cout
map::operator[]
在映射中创建元素(如果它们不存在),这就是为什么在
const
对象上不允许创建元素的原因。您应该使用
find()


(一些链接在右边的问题已经回答了这个问题:例如,我将投票以重复的形式结束此问题)

如果您查看map的声明,您将看到它不是
const
限定的,这就是为什么不能在
const std::map上调用它的原因。它不是const的原因是,如果map中不存在键,它会创建它。您应该改为使用或获取元素。

坦率地说,有办法问题中有很多无关的废话。人们不想浪费时间读这些,他们只想问这个问题。很抱歉,克里斯。这个话题真的很枯燥,我在周末晚上(PST)试着让它轻松一些。我尝试了一些TL;DRs(甚至是大写!)显然,我们也很重视幽默,但我们还很重视幽默感,但这并不是真正的问题。也许最值得注意的例外是最高级别的C++问题。如果你环顾四周,你会看到评论很高,因为它们很有趣,不是因为它们有用。erstood(并同意)-这绝对是一个(可能需要更改用户名吗?)的前台时刻,可以看到已经在一个远短得多的帖子中被问到的重复问题链接。thudPerfect,谢谢-完全忘记了可以创建密钥(如果它不存在)。再次感谢。是的,当然,Tony..我做了一个搜索(诚实的引擎!)但我没有看到……或者错过了——今天我盯着程序员字体看得太久了。
std::map<std::string, double>& aSpecificMap = const_cast<std::map<std::string, double>&>(theNamedNumberMapVector[theIndex]);