0

I have a set. It is of the form set<pair<string,int> > stockSet I want find if the above set has an entry for a given string that is first element. Also to find the value of 2nd part of the pair, that is int given the first element of the pair which is string.

I know how to do it with map and also single element set. But I am unable to figure out how to do this, need help with syntax.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70

1 Answers1

0

You can't figure it out because you can't do this.

The elements in a set are "complete" elements. Just because you see a std::pair in there, and you think that the set contains two elements, it doesn't mean that it is. The set contains a std::pair, a single, complete, element.

If you have another std::pair, somewhere, you can search the set to see if there's an equivalent pair in there. But if you only have half of the object that the set contains, you really can't do it.

The only options I see here are:

  • iterate over the set manually, until you do or do not find what you're looking for.

  • If there's a minimum int value you expect to be in there, you can use lower_bound(), passing a std::pair with the minimum value for the int portion, and the string you're search for, and see what lower_bound() digs up.

  • perhaps reconsider your decision to use a std::set for whatever purpose you're using. Perhaps a std::set, containing a std::pair, isn't really the appropriate container for your requirements.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • OK, I think I am better off using a Map. But i need one other help. If I create a set with elements as pair and I want it to be sorted based on first value. How can i do that? I mean how do I specify that sorting has to be done based on first element since set by default is sorted. – Vasavi Manasa Mar 07 '16 at 05:05
  • @VasaviManasa - just define a custom comparator for your set. – Sam Varshavchik Mar 07 '16 at 11:40