c – 从标记为const的函数中的std :: map中检索项目
发布时间:2020-12-16 09:48:06 所属栏目:百科 来源:网络整理
导读:考虑以下C代码: // A.hclass A {private: std::mapint,int m; int getValue(int key) const;};// A.cppint A::getValue(int key) const { // build error: // No viable overloaded operator[] for type 'const std::mapint,int' return m[key];} 如何从m中
考虑以下C代码:
// A.h class A { private: std::map<int,int> m; int getValue(int key) const; }; // A.cpp int A::getValue(int key) const { // build error: // No viable overloaded operator[] for type 'const std::map<int,int>' return m[key]; } 如何从m中获取值,使其在const函数的上下文中工作? 解决方法
您最好的选择是使用at()方法,它是const,如果找不到密钥则抛出异常.
int A::getValue(int key) const { return m.at(key); } 否则,在未找到密钥的情况下,您必须决定返回什么.如果在这些情况下可以返回值,则可以使用 int A::getValue(int key) const { auto it = m.find(key); return (it != m.end()) ? it->second : TheNotFoundValue; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |