如何执行两个容器中的元素之间的两两二元操作?容器、元素、两个、操作

2023-09-11 02:11:08 作者:谁共你伴.

假设我有两个向量的std ::矢量< uint_32> A,B; ,我知道是同样大小的

Suppose I have two vectors std::vector<uint_32> a, b; that I know to be of the same size.

有没有C ++ 11范例做了按位与中的所有成员 A 之间 B ,并把结果的std ::矢量&lt; uint_32&GT; ℃;

Is there a C++11 paradigm for doing a bitwise-AND between all members of a and b, and putting the result in std::vector<uint_32> c;?

推荐答案

一个拉姆达应该做的伎俩:

A lambda should do the trick:

#include <algorithm>
#include <iterator>

std::transform(a.begin(), a.end(),     // first
               b.begin(),              // second
               std::back_inserter(c),  // output
               [](uint32_t n, uint32_t m) { return n & m; } ); 

更妙的是,由于@Pavel和全部C ++ 98:

Even better, thanks to @Pavel and entirely C++98:

#include <functional>

std::transform(a.begin(), a.end(), b.begin(),
               std::back_inserter(c), std::bit_and<uint32_t>());