1

Below is my code where i am inserting some values in map where two iterator it2 holds key and value "1-1","yes" and iterator it4 holds"1-1","no" . As i have inserted "1-1","yes" before "1-1","no" . The appearance of value "1-1","yes" in map is before "1-1","no". But when i try and compare which iterator comes before and which later then mycomp(it2->first,it4->first); or mycomp(it4->first,it2->first); both cases bool value returned is false. I know that map compares by Key and here key are same so probably it is returning false in both cases . But is there a way to determine whether a key related to which iterator is stored first and which last any how . I have to actually delete all values between a upper bound and lower bound . So i need to know in which is a forward direction for me While iterating for erasing the elements .

std::multimap<string, string> m;
std::multimap<string, string>::iterator it2;
std::multimap<string, string>::iterator it4;
std::multimap<string, string>::key_compare mycomp;
std::multimap<string, string> common;
mycomp = m.key_comp();

cout <<"Making Map m "<<endl;

m.insert(pair< string, string>("1-1"," yes" ));
m.insert(pair< string, string>("1-1"," no" ));

it2=m.lower_bound("1-0");
it4=it2++;

cout << "it2 values are : " << it2-> first << " and " << it2->second <<endl;
cout << "it4 values are : " << it4-> first << " and " << it4->second<< endl;
bool j =false;
j=mycomp(it2->first,it4->first);
if(j==true)
cout << " value of j returned is true" ;
if(j==false)
cout << " value of j returned is false" ;
Invictus
  • 4,028
  • 10
  • 50
  • 80
  • 1
    Generally, no. Use `euqal_range()` to get the range of *all* map entries with the same key, but beyond that, you're on your own. This is intentional: The purpose of the data structure is to store elements that are identified by the key value alone. If you need a stronger order, consider adding the second item to the ordering explicitly and use a `set` instead. – Kerrek SB Jan 03 '12 at 21:25
  • @Kerrek SB actually set just have value. Here in my case there if i use set i will have to break up key and value part by say strtok to extract individual value "1-1-yes" and lot of comparison will be there. Is there way we can do strict ordering for second item in map corresponding to keys? – Invictus Jan 03 '12 at 21:36
  • 2
    Yes, make a set ;-) Instead of `multimap`, make a `set>`, and use the `pair`'s natural lexicographic ordering. – Kerrek SB Jan 03 '12 at 21:55

1 Answers1

0

I do not think it is possible to know which iterator comes before. It is not even guaranteed that the ordering is respected. You may find more information here.

The key_compare object only compares key values to know whether the first key goes before the second. You may consider it as a minor than operator for keys. It returns false because both keys are equal.

Community
  • 1
  • 1
J. Calleja
  • 4,855
  • 2
  • 33
  • 54