我需要从对容器的排序 vector 中获取关于给定值的对应对。使用“二进制搜索”。怎么做?
#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为可选。如果在调用者处发现了一些可以做的比较,也可以只返回迭代器(请参见上面代码中的替代方法)。
关于c++ - 如何在C++中从成对的排序 vector 中获得与给定值有关的相应对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59917814/