问题
I need a binary search function.
I couldn't find any function in the standard library that will return the index of the found item, and if it wasn't found, will return the bitwise complement of the index of the next element that is larger than the item I looked for.
What is the function I am looking for?
Edit: I need to insert an item to a sorted vector and to keep it sorted. That's why I need to bitwise complement index.
回答1:
I'm quite certain the standard library doesn't include anything to do precisely what you're asking for.
To get what you want, you'll probably want to start from std::lower_bound
or std::upper_bound
, and convert the iterator it returns into an index, then complement the index of the value wasn't found.
回答2:
Clearly, this "will return the bitwise complement" is a big deal for you and I do not understand what you mean. That said, lookup std::upper_bound and see if it does what you want.
回答3:
There is no simple STL method which returns index against a sorted vector as far as I know, however you can use sample function below:
/**
* @param v - sorted vector instance
* @param data - value to search
* @return 0-based index if data found, -1 otherwise
*/
int binary_search_find_index(std::vector<int> v, int data) {
auto it = std::lower_bound(v.begin(), v.end(), data);
if (it == v.end() || *it != data) {
return -1;
} else {
std::size_t index = std::distance(v.begin(), it);
return index;
}
}
回答4:
int bin_search (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator low;
low = std::lower_bound(first,last,val);
if(low!=last && !(val<*low)){
return (low - first + 1);
}else{
return 0;
}
}
回答5:
using STL we can find the index
vector<int> vec{1,2,3,4,5,6,7,8,9} ;
vector<int> :: iterator index;
index=lower_bound(vec.begin(),vec.end(),search_data);
return (index-vec.begin());
来源:https://stackoverflow.com/questions/27431029/binary-search-with-returned-index-in-stl