提问人:yasara malshan 提问时间:1/26/2020 最后编辑:JVApenyasara malshan 更新时间:1/26/2020 访问量:108
如何在 C++ 中从排序的对向量中获取与给定值相关的对
How to get corresponding pair regarding to a given value from a sorted vector of pairs in C++
问:
我需要从对容器的排序向量中获取有关给定值的相应对。使用“二进制搜索”。怎么做呢?
#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 ? */
}
答:
3赞
n314159
1/26/2020
#1
将 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 作为可选。如果你发现一些东西,你也可以只返回迭代器,并在调用者处进行比较(参见上面代码中的替代项)。
评论
1赞
n314159
1/26/2020
谢谢,只需阅读名称并假设。lower_bound做到了我想要的
1赞
Olaf Dietsche
1/26/2020
这也行不通,因为条件是错误的。请改用 return 和。a.second < b.first
it->first > searched
1赞
Olaf Dietsche
1/26/2020
您应该提到,这至少需要 C++17,因为 .optional
0赞
n314159
1/26/2020
@Olaf,我一开始误读了这个问题,然后匆匆忙忙地进行了更正。我有点不同意第一个,它应该是等效的,因为没有重叠的间隔,我认为如果我们有两个触摸间隔,当前的测试可以正常工作,那就更明显了。
评论