Binary search for C ++ string array

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 an array of strings, is there a β€œsimple” way to find out?

+4
source share
2 answers

From SGI docs :

Please note that this is not necessarily the information that interests you! Usually, if you are checking if an element is present in a range, you want to know where it is (if it is present) or where it should be inserted (if it is absent). The lower_bound , upper_bound and equal_range provide this information.

I think the arguments behind this set of interfaces are that binary_search does not actually indicate whether it will return the beginning of the range of matches (if they match) or the end of the range, and you may want one or the other depending on whether you want you do something with the data already in the container, or add a new element (perhaps until the end of the corresponding range). Or you can transfer the entire range to something else. Consequently, various more or less specific interfaces for performing binary searches.

Unfortunately, you are unlikely to find others if you think, "I need a binary search program."

+5
source

I googled and found this http://www.cplusplus.com/reference/algorithm/binary_search/ ... This may be an easy way to achieve your goal

0
source

Source: https://habr.com/ru/post/1305495/


All Articles