C++ string array binary search
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", "M开发者_开发百科aine", "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?
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
, andequal_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".
I googled and found this http://www.cplusplus.com/reference/algorithm/binary_search/... It might be an easy way to accomplish your goal
精彩评论