Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;访问成员无序映射中的数据时,结构中的const方法编译错误_C++_Methods_Constants_Unordered Map - Fatal编程技术网

C++ C++;访问成员无序映射中的数据时,结构中的const方法编译错误

C++ C++;访问成员无序映射中的数据时,结构中的const方法编译错误,c++,methods,constants,unordered-map,C++,Methods,Constants,Unordered Map,我不明白我得到的编译错误。下面是我的用例的一个简化示例 #include <unordered_map> #include <iostream> #using namespace std; struct C{ unordered_map<int, string> m; C(){ m[1] = "one"; m[2] = "two"; } int method() const{

我不明白我得到的编译错误。下面是我的用例的一个简化示例

#include <unordered_map>
#include <iostream>

#using namespace std;

struct C{
    unordered_map<int, string> m;

    C(){
        m[1] = "one";
        m[2] = "two";
    }

    int method() const{
        const string s = m[2];
        return 42;
    }
};

int main() {
    C c;
    cout << c.method() << endl;
    return 0;
}
#包括
#包括
#使用名称空间std;
结构C{
无序地图m;
C(){
m[1]=“一”;
m[2]=“两个”;
}
int method()常量{
常量字符串s=m[2];
返回42;
}
};
int main(){
C C;
库特
不是
const
方法,因为它在不存在时插入元素。因此不能在常量
m
上使用它。请使用

std::unordered_map::at
相反

不是
const
方法,因为它在不存在时插入元素。因此不能在常量
m
上使用它。请使用

std::unordered_map::at

相反。

我打赌你不会因为“在重复辩论之前获得几张选票”而受到强烈的反对(例如被指控“滥用”),。生活太不公平了!@LightnessRacesinOrbit我确实提到了另一种只出现在评论中的查找方法。;)但说真的,如果这个答案违反了网站规则,他们可以去投诉国防部,否则,不喜欢这个的人就倒霉了。我不会参与任何元战争。完美的答案谢谢。@BaummitAugen:I co很遗憾,在我的情况下,他们确实同意了,接下来的是否决票和修改删除答案。Pfft。@Lightness Racesinorbit Meta police会做Meta police会做的事。vOvBet你不会因为“在欺骗前投了几票”而受到强烈的反对(例如被指控“滥用”),。生活太不公平了!@LightnessRacesinOrbit我确实提到了另一种只出现在评论中的查找方法。;)但说真的,如果这个答案违反了网站规则,他们可以去投诉国防部,否则,不喜欢这个的人就倒霉了。我不会参与任何元战争。完美的答案谢谢。@BaummitAugen:I co太同意了!不幸的是,在我的情况下,他们这样做了,接下来就是对答案的向下投票和修改删除。Pfft。@LightnessRacesinOrbit元警察会做元警察会做的事。vOv