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} .
Asked
Active
Viewed 59 times
0
-
3You 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
-
1it 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
-
1Depending 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 – dfrib Oct 01 '17 at 14:54` (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). -
Possible duplicate of [bitwise operations on vector
](https://stackoverflow.com/questions/4048749/bitwise-operations-on-vectorbool) – dfrib Oct 01 '17 at 14:57
2 Answers
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
-
1Also 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
-
If the arrays are fixed size, you can also consider using an `std::bitset`. – M. Yousfi Oct 01 '17 at 14:40