0

I have two vectors: A = {1,0,1,1}, B = {0,1,1,1}. How can I apply or operator on these two so that i could get a vector: C = {0,0,1,1} .

Prateek Oraon
  • 101
  • 1
  • 8
  • 3
    You say you want to use OR, but your expected output suggests AND. Which is it? And what have you tried? – Carcigenicate Oct 01 '17 at 14:33
  • 1
    it sounds like you want an AND operator, not an OR operator... `1011` V `0111` = `1111` vs `1011` ^ `0111` = `0011` – M Y Oct 01 '17 at 14:33
  • 1
    Depending on your use case, [`std::valarray`](http://en.cppreference.com/w/cpp/numeric/valarray) might be worth considering. – Rakete1111 Oct 01 '17 at 14:36
  • As the question is tagged `vector` it seems you are looking for a dynamic bitset. For this, `std::vector` as well as `std::vector` (due to the peculiar nature of the latter) should be avoided. If a dynamic bitset is indeed what you are looking for, the Q&A I've linked to below might be an appropriate duplicate for this question. See also [`std::bitset`](http://en.cppreference.com/w/cpp/utility/bitset) and [`boost::dynamic_bitset`](http://www.boost.org/doc/libs/1_65_1/libs/dynamic_bitset/dynamic_bitset.html). – dfrib Oct 01 '17 at 14:54
  • Possible duplicate of [bitwise operations on vector](https://stackoverflow.com/questions/4048749/bitwise-operations-on-vectorbool) – dfrib Oct 01 '17 at 14:57

2 Answers2

3
std::vector<int> C;
std::transform(A.begin(), A.end(), B.begin(),
    std::back_inserter(C), std::logical_and<int>());
Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • 1
    Also need to check `B.size() >= A.size()`. The behaviour is undefined if this isn't true. – Peter Oct 01 '17 at 14:39
1

You can just loop through them element-wise using indices

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> A = {1, 0, 1, 1};
    std::vector<int> B = {0, 1, 1, 1};

    std::vector<int> C(A.size());
    for (std::size_t i = 0; i < A.size(); ++i)
    {
        C[i] = A[i] && B[i];
    }

    for (auto value : C)
    {
        std::cout << value << " ";
    }
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218