gpt4 book ai didi

c++ - 如何将 const 字符串值放入 map

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:14:40 25 4
gpt4 key购买 nike

我想创建一个 map ,

std::map <MESSAGE_CATEGORY, const std::string> m_mapResponseDesc;

我正在使用 operator[]在 map 中附加一个值:

m_mapResponseDesc[STATUS_LIMIT] = "Limit has been exceeded";

STATUS_LIMIT类型为 enum .

我遇到错误:

error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)

请指出我做错了什么。我没有得到任何线索。

最佳答案

由于 operator[] 返回一个引用(对 const std::string),您将需要使用 insert() 方法相反。

#include <map>
#include <string>
using namespace std;

int main()
{
std::map<int, const std::string> m;
m.insert(std::make_pair(1, "Hello"));
return 0;
}

C++11 更新:

您现在可以更轻松地做到这一点:

std::map<int, const std::string> status = {
{200, "OK"},
{404, "Not Found"}
};

关于c++ - 如何将 const 字符串值放入 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18722669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com