search based on two keys

Pages: 12
A different possibility is to use a pair of dates (strings) as the key type in a single map. The std::pair template automatically generates a comparison function that is sufficient for this.

Here's an example:
1
2
3
4
5
6
7
8
9
10
  using std::map;
  using std::string;
  typedef std::pair<string, string> str_pair;

  map<str_pair, double> m;
  m[str_pair("foo", "bar")] = 3.14;
  m[str_pair("bar", "foo")] = 6.28;
  std::cout << m[str_pair("foo", "bar")] << std::endl; // 3.14
  std::cout << m[str_pair("bar", "foo")] << std::endl; // 6.28
  std::cout << m[str_pair("foo", "foo")] << std::endl; // 0 
Last edited on
Thanks for pointing this out. Yes, I can store my data in a data structure like:

map<pair<string, string>, vector<Data> >

that's neat too ;)

Thanks again.

John.
Btw, I just wanted to add this ...
As a beginner, when I read about map vs multimap, text books always say (at least the ones I've looked at) use maps if your key is unique and multimap when you want to have more entries with the same key.

From this forum I leaned how to use maps for the latter case as well, using something like,
map<string, vector<Data> >

Though simple, it never occured to me before that you can do that ; ). Furthermore, text books always talk about using pairs when inserting into a map or a multimap. Again, from this forum I found how to use convenient [] notation.

Besides reading text books, I guess there's a lot to learn from how things are done in practice.

Thanks everyone for your advice and help.

John
Topic archived. No new replies allowed.
Pages: 12