map<string, string> how to insert data in this map?

Viewed 104614

I need to store strings in key value format. So am using Map like below.

#include<map>
using namespace std;
int main()
{
    map<string, string> m;
    string s1 = "1";
    string v1 = "A";

    m.insert(pair<string, string>(s1, v1)); //Error
}

Am getting below error at insert line

error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const std::string'

I tried make_pair function also like below, but that too reports the same error.

m.insert(make_pair(s1, v1));

Pls let me know what's wrong and what's the solution for above problem. After solving above problem, can i use like below to retrieve value based on key

m.find(s1);
7 Answers

Here is the way to set up map<...,...>

static std::map<std::string, RequestTypes> requestTypesMap = {
   { "order",       RequestTypes::ORDER       },
   { "subscribe",   RequestTypes::SUBSCRIBE   },
   { "unsubscribe", RequestTypes::UNSUBSCRIBE }
};

You have several possibilities how store strings in key value format now:

m["key1"] = "val1";
m.insert(pair<string,string>("key2", "val2"));
m.insert({"key3", "val3"}); // c++11

And traverse it in c++11:

for( auto it = m.begin(); it != m.end(); ++it )
{
  cout << it->first; // key
  string& value = it->second;
  cout << ":" << value << endl;
}
Related