映射<字符串,字符串>在类中
map<string, string> in class
当我尝试在VS2010中编译以下代码时,提示错误C2678。
#include <string>
#include <map>
using namespace std;
class test
{
private:
map<string, string> data;
public:
test(){};
~test(){};
public:
const string & get(const string & key)const{return data[key];}; //error C2678
bool set(const string & key, const string & value){data[key]=value;return true;};
};
void main()
{
const string key="Hello world!";
const string value="I'm coming!";
test t;
t.set(key,value);
t.get(key);
}
但是当我把它作为函数,比如
#include <string>
#include <map>
using namespace std;
bool set(const string & key, const string & value, map<string, string> & data)
{
data[key]=value;
return true;
}
const string & get(const string & key, map<string, string> & data)
{
return data[key];
}
void main()
{
const string key="Hello world!";
const string value="I'm coming!";
map<string, string> data;
set(key, value, data);
get(key;
}
可以编译并运行。
有谁知道是什么问题吗?
您已经将测试类的get成员函数声明为const。但是std::map
operator[]
是一个非const函数,所以它不能从const函数调用。请使用find
函数。
operator[]
是非const的原因是因为如果键不存在,那么它将它与默认构造值一起插入到映射中。
要在const
映射中查找对象,需要使用find
成员函数,不能使用operator[]
:
const string & get(const string & key)const {return data.find(key)->second;}
相关文章:
- 如何使用Visual Studio 2008将字符串映射到函数?
- 我可以比朴素哈希表更快地将随机字符串映射到两个类吗?
- 自定义哈希表实现-将字符串映射到整数时出现内存错误
- 在声明unordered_map的错误中,将字符串映射到模板
- 将字符串映射到矢量或将不同的键映射到一个值
- 使用 C++11 可变参数模板初始化枚举到字符串映射
- 将字符串映射到 C++ 中的类函数
- 根据该输入字符串将字符串映射到不同的类
- 如何访问 <int,字符串>映射中的特定字符?
- C字符串映射键
- C 索引中的字符串映射而无需分配
- 实现将字符串映射到 C++ 中的数组的哈希表。我一直在"Debug Assertion Failed",我不知道为什么
- 将字符串映射到无符号 int 到无符号 int 的映射
- C++ std::将字符串映射到指针
- c++将大型数字字符串映射到数字字符串范围
- 使用字符串映射的向量时可能会发生内存泄漏C++
- 一个比较2个字符串映射的通用C++规则引擎
- 如何在c++中仅针对键的子集有效地比较两个字符串映射
- 如何将用户输入(字符串)映射到Enum值
- 我如何消除这个枚举到字符串映射代码的样板文件?