user6013878
user6013878

Reputation: 41

bitwise OR operation on std::array

I have a c++ std::array typedef'd as follows:

typedef std::array<uint64_t, 2>MyType;

If I have two instances of "MyType", and I wanted to perform bitwise "OR" on these two instances, I currently have code as follows:

MyType instance1 { 11, 22 };
MyType instance2 { 33, 44 };
MyType output {0, 0};
for(int i = 0; i < 2; ++i)
{
  output[i] |= instance1[i];
  output[i] |= instance2[i];
}

The results of running this are

output[0] = 43; output[1] = 62;

My question is Is there any other way of doing this bitwise "OR" (other than looping through the elements one-by-one?)

Upvotes: 0

Views: 595

Answers (1)

Aziuth
Aziuth

Reputation: 3902

You can use std::transform, which then does the iterations for you, as I did here:

#include <iostream>
#include <array>
#include <algorithm> // std::transform
#include <functional> //std::bit_or

typedef std::array<uint64_t, 2 > MyType;

int main()
{
    MyType instance1 { 11, 22 };
    MyType instance2 { 33, 44 };
    MyType output {0, 0};

    std::transform(output.begin(), output.end(), instance1.begin(), output.begin(), std::bit_or<uint64_t>());
    std::transform(output.begin(), output.end(), instance2.begin(), output.begin(), std::bit_or<uint64_t>());

    for(int i = 0; i < 2; ++i) std::cout << output[i] << std::endl;
}

Demonstration: http://www.cpp.sh/94cs4

Note that I find your original code to be more readable than this. I'd use std::transform in more complex situations only.

That said, what are you actually trying to solve?
If you look for the convenience of easy component-wise operations as one would find for example in Matlab, not to my knowledge. You could write your own container class similar to std::vector and std::array and have certain operators, like | in your case, to work with those.

Upvotes: 1

Related Questions