Search code examples
c++c++11stdvectorboolean-operations

How to perform boolean operations in c++


I want to add two bolean vectors

vector<bool> v1= {0,0,1}
vector<bool> v2= {1,0,1}
vector<bool> resultedVector = v1+v2 

The answer should be:

resultedVector = {1,1,0};

Does anyone know, how to do in c++/c++11 ? I want to increment every time given boolean vector by 1. And just want to use binary operations. Or could create bolean truth table of given number of variable.


Solution

  • To perform binary addition in C++, you can use the function described here: Adding binary numbers in C++

    I implemented the function from that link to fit your specifications like this:

    std::vector<bool> add(const std::vector<bool>& a, const std::vector<bool>& b)
    {
            bool c;
            std::vector<bool> result;
            for(int i = 0; i < a.size() ; i++){
                    result.push_back(false);
                    result[i] = ((a[i] ^ b[i]) ^ c); // c is carry
                    c = ((a[i] & b[i]) | (a[i] & c)) | (b[i] & c);
            }
            return result;
    }
    

    This function takes two vectors of bools (and assumes they are the same size) and returns their result vector. Obviously this function doesn't handle overflow or numbers of different sizes. You can modify it yourself if you need those capabilities. Also, you seem to be talking about an overloaded operator for a bool vector, and you can do that by checking out operator overloading, but this logic will allow you to add two boolean numbers stored in vectors.