找出两个范围(其中一个是排序的)是否有一个共同的元素。

时间:2021-10-29 12:47:39

I wrote the following code that does it:

我写了以下代码:

std::vector<int> vec;
std::vector<int> sortedRange;
// ...
bool hasCommonElement = 
    std::any_of(begin(vec), end(vec),
                std::bind(std::binary_search, begin(sortedRange), end(sortedRange), _1));

The compiler is complaining that it cannot find out which overload of binary search I mean. Do you have any other elegant solution? Or a good reason why it does not compile?

编译器抱怨说,它无法找出我说的二分查找的重载。你有其他优雅的解决方案吗?或者为什么它不能编译?

Edit

编辑

  • I do know I can use a lambda. But here the bind seems more elegant (if I had generic lambdas, it would be great! But I don't).
  • 我知道我可以用。但是这里的绑定看起来更优雅(如果我有通用的lambdas,那就太棒了!)但我不)。
  • I do know that I can qualify the iterator type: binary_search<std::vector<int>::iterator>. But it is even less elegant.
  • 我知道我可以限定迭代器类型:binary_search <:vector> ::iterator>。但它甚至更不优雅。
  • I know I can also do it by sorting "vec" and using set_intersection. But this is more complicated too.
  • 我知道我也可以通过对“vec”和set_交集进行排序。但这也更复杂。

2 个解决方案

#1


1  

You can do it with a lambda instead of bind:

你可以用lambda代替bind:

bool hasCommonElement = any_of(begin(vec), end(vec), [&](int x) {return binary_search(begin(sortedRange), end(sortedRange), x);});

#2


1  

You have two issues. The binary_search is a template (which parameters are not deduced) and you need to qualify the placeholder:

你有两个问题。binary_search是一个模板(没有推导出参数),您需要限定占位符:

#include <vector>
#include <algorithm>
#include <functional>

int main( {
    std::vector<int> vec;
    std::vector<int> sortedRange;
    bool hasCommonElement =
        std::any_of(
            begin(vec), end(vec),
            std::bind(
                std::binary_search<std::vector<int>::iterator, int>,
                begin(sortedRange),
                end(sortedRange),
                std::placeholders::_1));
    return 0;
}

#1


1  

You can do it with a lambda instead of bind:

你可以用lambda代替bind:

bool hasCommonElement = any_of(begin(vec), end(vec), [&](int x) {return binary_search(begin(sortedRange), end(sortedRange), x);});

#2


1  

You have two issues. The binary_search is a template (which parameters are not deduced) and you need to qualify the placeholder:

你有两个问题。binary_search是一个模板(没有推导出参数),您需要限定占位符:

#include <vector>
#include <algorithm>
#include <functional>

int main( {
    std::vector<int> vec;
    std::vector<int> sortedRange;
    bool hasCommonElement =
        std::any_of(
            begin(vec), end(vec),
            std::bind(
                std::binary_search<std::vector<int>::iterator, int>,
                begin(sortedRange),
                end(sortedRange),
                std::placeholders::_1));
    return 0;
}