Binary search with returned index in STL?

前端 未结 6 1809
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 11:42

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,

6条回答
  •  孤城傲影
    2021-01-12 12:16

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

提交回复
热议问题