How can I parse a char pointer string and put specific parts of it in a hash map in C++?

Lets say I have a char pointer like this:

const char* myS = "John 25 Los Angeles";

I want to parse this string and put it in a hashmap, so I can retrieve the person's age and city based on his name only. Example:

1
2
3
4
5

std::unordered_map<string, string> myMap;

john_info = myMap.find("John"); //john_info returns "25 Los Angeles"


How can I do this to return all of John's info in an elegant way ? I come from a Java background and I really want to know how this is properly done in C++. That would also be cool if you can show me how to do this using a boost map (if it is easier that way). Thank you.

with what you have, its pretty much
myMap["John"] = myS; //you should use string, not char*, in c++. Char * is C code that c++ accepts but is only used if necessary.

then if you find on "John" (case sensitive!) it will give you back myS data.

a little smarter and more OOPish might be to make a class with a string name, int age, string city or whatever and stuff a string key and class as data into the map.

I am not aware that boost's maps are any better than c++. Boost tends to LEAD c++; its tools are frequently adopted into the language after being kicked around for a few years. Its probably pretty close, but I haven't studied this specific container.

a really simple quick example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

char sp = ' ';

struct xdata
{
  string name;
  int age{};
  string city; 	
  xdata(){};
  xdata(int a, string n, string c)
  {
    age = a; name = n; city = c;	  
  }
};

int main()
{
   xdata d(25, "John"s, "L. A.");
   unordered_map<string, xdata> datamap;
   datamap[d.name] = d;
   xdata r = datamap["John"]; //warning, if not there, inserts it when using [] 
   cout << r.name << sp << r.age << sp << r.city<<endl;   
}
Last edited on
Topic archived. No new replies allowed.