0

I am using an object as a key for a multimap. The object is a custom date class which I created. I was just wondering if it is possible to use a variable found in the object for equal_range()?

That is check against the month variable in my custom date object.

That is something like this (pseudo code).

int january = 1;
foundValues = myMultimap.equal_range(january);

for (it=foundValues.first; it!=foundValues.second; ++it)
{
  cout << " " << (*it).second;
  cout << endl;
}

Will this go through each key object and check if the variable inside that object is equal to "january", then return the value paired to the key?

Thank you.

  • 2
    Why don't you just use the month as the key in the first place? – Xymostech Nov 25 '12 at 18:31
  • If your date includes the year it won't work, as "all days in January of all years" is not a range. – n. m. could be an AI Nov 25 '12 at 18:49
  • Xymistech- The reason is because I need to search all values of a certain month in a certain year. That's why I used a date class for the key. I tried using a string containing the full date in the format did/mm/yyyy but when I do a inorder travelsal, the multi map only sort by the days. So when you look at the output the days are in order but the month and year are not. – aelindgard Nov 26 '12 at 02:26

1 Answers1

0

The search members of the associative container work on the key only. Theyexist because they take advantage of the container's internal structure which guarantees finding values (or their absence) in O(log(n)) time (where n is the number of elements in the container).

If you want to find all eleements in a sequence matching a condition you probably want to use std::copy_if() with a suitable predicate.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Ah. Thank you. Can I just confirm the function again. copy_if(mymulti.begin(), my multi.end(), compmonth()); Something like this? – aelindgard Nov 26 '12 at 02:28
  • You'd call it as `std::copy_if(multimap.begin(), multimap.end(), std::back_inserter(target), compmonth())`. This algorithm is new in C++ 2011. If you need to use C++ 2003, you can use `std::remove_copy_if()` instead but, obviously, you need to negate the predicate. – Dietmar Kühl Nov 26 '12 at 06:47