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,
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 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;
}
}