How do I perform a pairwise binary operation betwe

2019-01-23 03:59发布

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

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;?

3条回答
趁早两清
2楼-- · 2019-01-23 04:22

Just an idea, not C++11 specific: Maybe you could step through the arrays 8 bytes at a time using uint_64, even though the actual array is composed of 32-bit integers? Then you would not rely on e.g. SSE, but still get fast execution on many CPUs that have 64-bit wide registers.

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-23 04:30

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; } ); 

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>());
查看更多
祖国的老花朵
4楼-- · 2019-01-23 04:41

If you're going to be doing this a lot, on large arrays, check out the linear algebra libraries mentioned in https://stackoverflow.com/search?q=valarray. Many of them will take advantage of special instructions to get the answer faster.

查看更多
登录 后发表回答