Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put const string value in map

Tags:

c++

stl

I want to create a map ,

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

I am using operator[] to append a value in the map:

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

STATUS_LIMIT is of type enum.

I am getting error:

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)

Please point out what mistake I have done. I am not getting any clue.

like image 573
Bhupesh Pant Avatar asked Dec 20 '22 00:12

Bhupesh Pant


1 Answers

Since operator[] returns a reference (to a const std::string) you will need to use the insert() method instead.

#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;
}

Update for C++11:

You can do this even easier now:

std::map<int, const std::string> status = {
        {200, "OK"},
        {404, "Not Found"}
    };
like image 76
Chad Avatar answered Jan 06 '23 07:01

Chad