如何在没有迭代器的情况下使用 std::for_each + std::execution::p ar?
How to use std::for_each + std::execution::par without iterator?
我想使用std::for_each(std::execution::par, ...)
tbb::parallel_for
风格。
tbb::parallel_for(0, n, [](const tbb::blocked_range<size_t>& r) { f(r); });
但是,std::for_each()
只接受迭代器。
std::vector<int32_t> v(0, n);
std::for_each(std::execution::par,
v.begin(),
v.end(),
[&](int32_t& i) { f(i); });
如何解决这个问题?
大多数标准算法都在迭代器上运行,这就是它们的工作方式,因此它们可以与多个容器一起使用。
但是,std::vector
使用随机访问迭代器,因此您可以将索引应用于begin
迭代器,例如:
template<typename T, typename Callable>
void my_parallel_for(std::vector<T> &v, size_t startIdx, size_t endIdx, Callable c)
{
std::for_each(std::execution::par,
v.begin()+startIdx,
v.begin()+endIdx,
c);
}
std::vector<int32_t> v;
...
my_parallel_for(v, 0, n, [&](int32_t& i) { f(i); });
我终于找到了解决方案。
class Iterator
: public std::iterator<std::random_access_iterator_tag, int64_t, int64_t>
{
public:
Iterator() = default;
Iterator(int64_t index) : index_(index) {}
const int64_t& operator*() const { return index_; }
const void operator++() { ++index_; }
bool operator!=(const Iterator& lhs) const { return index_ != lhs.index_; }
const int64_t operator+(const Iterator& lhs) const { return index_ + lhs.index_; }
int64_t operator-(const Iterator& lhs) const { return index_ - lhs.index_; }
private:
int64_t index_;
};
std::for_each(std::execution::par,
Iterator(0),
Iterator(n),
[&](int64_t idx) { f(idx); });
您可以使用tbb::counting_iterator
(https://www.threadingbuildingblocks.org/docs/help/reference/iterators/counting_iterator.html(
auto begin = tbb::counting_iterator<int>(0);
std::for_each(std::execution::par,
begin,
begin + n,
[&](int32_t& i) { f(i); });
Boost也有它:https://www.boost.org/doc/libs/1_71_0/libs/iterator/doc/counting_iterator.html
相关文章:
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- std::memory_order for std::atomic:<T>:wait
- 在基于范围的 for 循环期间插入 std::list 的后面
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 运算符 << 操作加载的 API for std::endl?
- google test PrintTo for std::set<std::string>
- std::memcpy vs std::copy_n for legacy c structs
- C++11 基于范围的 for 循环,用于 std::list
- For-loop或std::any_of,我应该使用哪一个?
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- std::hash for std::chrono::duration
- 如何修复以下错误"no match for call to '(std::tr1::shared_ptr<_iobuf*>) (FILE*&)'"
- 访问类的 std::vector 与 for 循环中的 custum 类对象
- Hash for a std::pair, for use in an unordered_map
- 计算使用 C++ std 函数而不是 for 循环的大 O
- 使用 OpenMP 在并行 for 循环中使用 std::cout
- 使用 std::vector<Particle> 粒子;函数 .at() 不能与迭代器一起使用,它作为 for 循环中的参数
- C++ SFINAE : is_constructible for const char[] vs std::strin
- 使用 std::min "no matching function for call to ‘min(<brace-enclosed initializer list>)’"时出错
- 类型安全 - all_of/ any_of/ none_of for std::tuple