bjskishore123
bjskishore123

Reputation: 6342

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

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);

Upvotes: 24

Views: 121091

Answers (7)

Alexey Tkach
Alexey Tkach

Reputation: 71

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

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

Upvotes: 7

TadejP
TadejP

Reputation: 1042

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

Upvotes: 4

badrequest
badrequest

Reputation: 11

The s1 is an integer you are hoping pass as string...thats likely the main cause of the error!!

Upvotes: -1

default
default

Reputation: 11635

I think it has to do with the fact that <map> doesn't include <string>, but <xstring>. When you are adding elements to the map it needs to find the correct position in the map by sorting. When sorting, map tries to locate the operator <, from which it finds the correct location for the new element. However, there is no operator < for the definition of string in <xstring>, thus you get the error message.

Upvotes: 1

Daren Thomas
Daren Thomas

Reputation: 70314

Could you try this:

#include<string>

It seems the compiler doesn't know how to compare strings. Maybe she doesn't know enough about strings yet, but is too focused on your map to figure that out ATM.

Upvotes: 10

Etienne de Martel
Etienne de Martel

Reputation: 36852

I think you miss a #include <string> somewhere.

Upvotes: 42

tdammers
tdammers

Reputation: 20721

Try m[s1] = v1; instead.

Upvotes: 5

Related Questions