如何从 C++ 中的排序对向量中获取与给定值相关的对应对

How to get corresponding pair regarding to a given value from a sorted vector of pairs in C++

我需要从对容器的排序向量中获取关于给定值的对应对。使用 'binary search'。怎么做?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    vector<pair<int,int>> values;
    values.push_back(make_pair(6,9));
    values.push_back(make_pair(2,5));
    values.push_back(make_pair(12,15));

    sort(values.begin(), values.end()); // sorting the vector according to 'first' value

    /*then the vector be like [(2,5), (6,9), (12,15)]*/
    /*assume : no duplicate or overlapped pairs*/

    /* I need to implement a function to get the corresponding pair related to a given value using 'binary search' method*/
    /*eg:
      if given_value = 7, then function should be return (6,7)
      if given_value = 10, then function shold be return NULL
      how i do this. is there a predefined way to do this ? */
}

std::lower_bound 与自定义比较器一起使用:

std::optional<std::pair<int,int>> find(const std::vector<std::pair<int, int>>& vec, int searched) {
  auto it = std::lower_bound(cbegin(vec), cend(vec), std::pair<int, int>{searched, 0}, [](const auto& a, const auto& b) {return a.first < b.first;});
  if(it == cend(vec) || searched < it->first) { // nothing found, return nullopt
    return {};
    // alt: return cend(vec);
  }
  return {*it}; // return value wrapped in optional
  // alt: return it;
}

注意:这需要 C++17 作为可选。如果你找到了一些东西并在调用者处进行比较,你也可以只 return 迭代器(参见上面代码中的替代方案)。