string Haystack[] =  { "Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia",
                 "Florida", "Georgia", "Guam", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", 
                 "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", 
                 "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Northern Mariana Islands", "Ohio", "Oklahoma",
                 "Oregon", "Pennsylvania", "Puerto Rico",  "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "US Virgin Islands", "Utah",
                 "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"};

 string Needle = "Virginia";

 if(std::binary_search(Haystack, Haystack+56, Needle))
      cout<<"Found";

If I also wanted to find the location of the needle in the string array, is there an "easy" way to find out?

share|improve this question

feedback

2 Answers

up vote 5 down vote accepted

From the SGI docs:

Note that this is not necessarily the information you are interested in! Usually, if you're testing whether an element is present in a range, you'd like to know where it is (if it's present), or where it should be inserted (if it's not present). The functions lower_bound, upper_bound, and equal_range provide this information.

I think the reasoning behind this set of interfaces is that binary_search doesn't really indicate whether it'll return the start of the range of matches (assuming there are matches) or the end of the range, and you might want one or the other depending on whether you want to do something with data already in the container or add a new item (possibly to the end of the matching range). Or you might want to pass the whole range on to something else. Hence the various more or less specific interfaces to perform a binary search.

Unfortunately, you're not particularly likely to find the other ones if you're thinking, "I need a binary search routine".

share|improve this answer
+1 @Michael Man my answer was totally wrong :) – AraK Mar 30 '10 at 0:01
feedback

I googled and found this http://www.cplusplus.com/reference/algorithm/binary_search/... It might be an easy way to accomplish your goal

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.