Reputation: 329
I have an array of integers called test
containing 7 elements,I want to write an if statement to check if the 6 first values of the array are equal to a certain collection of values,what I tried was:
if (test == {1, 0, 1, 0, 0, 0} ) {
//statement(s)
}
However,the line containing the condition gives me an "expected an expression error",what am I doing wrong? Thanks in advance.
Upvotes: 0
Views: 171
Reputation: 126
Here is a way to do it (if your test
is an std::array
):
#include <algorithm>
...
std::vector<int> v({1, 0, 1, 0, 0, 0});
if( (v.size()==test.size()) && std::equal(test.begin(), test.end(), v.begin()) ) {
// statement(s)
}
or
#include <algorithm>
...
std::vector<int> v({1, 0, 1, 0, 0, 0});
if( std::equal(test.begin(), test.end(), v.begin(), v.end()) ) {
// statement(s)
}
Upvotes: 0
Reputation: 117308
C++17 versions using deduction guides:
std::array
std::array test{1, 0, 1, 0, 0, 0};
if(test == std::array{1, 0, 1, 0, 0, 0}) {
std::cout << "equal\n";
}
std::vector
std::vector test{1, 0, 1, 0, 0, 0};
if(test == std::vector{1, 0, 1, 0, 0, 0}) {
std::cout << "equal\n";
}
Upvotes: 2
Reputation: 8228
If you use std::array
you can simply rely on operator==
std::array<int, 7> a1 = {1, 2, 3, 4, 5, 6, 7};
std::array<int, 7> a2 = {2, 3, 4, 5, 6, 7, 8};
std::cout << "a1 == a1 " << (a1 == a1) << std::endl;
std::cout << "a1 == a2 " << (a1 == a2) << std::endl;
However, if for some reason you need to use C-style array, then you can use std::memcmp
, which will compare the arrays byte by byte:
int ca1[7] = {1, 2, 3, 4, 5, 6, 7};
int ca2[7] = {2, 3, 4, 5, 6, 7, 8};
std::cout << "ca1 == ca1 " << (std::memcmp(ca1, ca1, sizeof(ca1)) == 0) << std::endl;
std::cout << "ca1 == ca2 " << (std::memcmp(ca1, ca2, sizeof(ca1)) == 0) << std::endl;
Note that you need to compare the std::memcmpy
result with 0, which means that they are equal. reference However, in this approach you should first check if the dimensions are equal.
Upvotes: 0