gpt4 book ai didi

c++ - 按值排序的 std::find 和 std::any_of

转载 作者:行者123 更新时间:2023-12-01 22:08:26 30 4
gpt4 key购买 nike

假设我有一个std::vector<int>并想知道它是否包含 3或者将迭代器获取到 3

我不想使用std::setstd::multiset无论出于何种原因。

我想在 std::execution::par_unseq 中执行此操作模式。
我看到的两个选项是 std::any_ofstd::find ,但他们并没有完全为我做到这一点。

#include <execution>
#include <functional>
#include <iostream>
#include <vector>

int main()
{
std::vector vec{ 1, 1, 1, 1, 1, 3, 3, 3, 3 };

bool contains{ std::any_of(
std::execution::par_unseq,
vec.begin(), vec.end(),
std::bind(std::equal_to{}, std::placeholders::_1, 3)) };

auto found{ std::find(std::execution::par_unseq, vec.begin(), vec.end(), 3) };

return 0;
}

std::any_of应该做我想做的事情,但是这个调用对于它所做的事情来说非常困惑。范围和std::bind_front会有帮助,但不是很多。

std::find 的问题是它必须找到 3第一次出现,这限制了它的效率,因为我不在乎哪个 3它找到了。

  • 是否有 std::any_of 的替代方案按值搜索?
  • 有吗std::find (和 std::search )找到任何匹配,不是第一个?

答案可达欢迎。

<小时/>

编辑:

为了澄清,我不想要一个检查包含并同时给我一个迭代器的函数。我正在寻找两个不同的函数(一个返回迭代器,一个返回 bool 值)。

最佳答案

Say I have an std::vector and want to know if it contains a 3 and optionally get the iterator to the 3.

我会将 std::any_of 版本打包到模板函数中,并使用 lambda 而不是 std::bind

请注意,std::any_ofpossibly implimented通过 std::find_if

#include <iostream>
#include <vector>
#include <algorithm> // std::find_if
#include <execution> // std::execution
#include <iterator> // std::distance

template<typename Iterator, typename Predicate>
auto find_any_of(Iterator first, Iterator last, Predicate pred) -> std::pair<bool, Iterator>
{
const Iterator iter = std::find_if(std::execution::par_unseq, first, last, pred);
return { iter != last, iter };
}

int main()
{
std::vector vec{ 1, 1, 1, 1, 1, 3, 3, 3, 3 };
// you call the function like
const auto [found, ele_iter]
= ::find_any_of(vec.cbegin(), vec.cend(), [](const int ele) { return ele == 3; });

if (found)
std::cout << "Element found at index: " << std::distance(vec.cbegin(), ele_iter);
return 0;
}

关于c++ - 按值排序的 std::find 和 std::any_of,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58874096/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com