Binary search with returned index in STL?

前端 未结 6 1810
佛祖请我去吃肉
佛祖请我去吃肉 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 11:57

    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.

    0 讨论(0)
  • 2021-01-12 11:59
    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;
      }
    }
    
    0 讨论(0)
  • 2021-01-12 12:06

    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());
    
    0 讨论(0)
  • 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<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;
        }   
    }
    
    0 讨论(0)
  • 2021-01-12 12:18
    int a = 0, b = n-1;
    while (a <= b) {
        int k = (a+b)/2;
        if (array[k] == x) 
        {
            // x found at index k
        }
        if (array[k] < x) a = k+1;
        else b = k-1;
    }
    
    0 讨论(0)
  • 2021-01-12 12:19

    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.

    0 讨论(0)
提交回复
热议问题