简体   繁体   中英

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", "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?

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".

我用Google搜索并发现了这个http://www.cplusplus.com/reference/algorithm/binary_search/ ......这可能是一种实现目标的简单方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM