How do I perform a pairwise binary operation between the elements of two containers?

后端 未结 3 1350
春和景丽
春和景丽 2020-12-14 18:17

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

Is there a C++11 paradigm for doing a bitwise-AND<

相关标签:
3条回答
  • 2020-12-14 18:55

    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.

    0 讨论(0)
  • 2020-12-14 18:57

    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.

    0 讨论(0)
  • 2020-12-14 18:59

    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>());
    
    0 讨论(0)
提交回复
热议问题