Search code examples
c++arrayscomparison

C++ compare std::array to std::array with only one variable


I know with my title it's hard to understand what I mean, but I'm new to C++ so I'm hoping you understand my problem, I'm trying to show you the issue with an example:

#include<conio.h>
#include<iostream>

#include <array>

using namespace std;

int main() {
    std::array<short int, 3> testarr = {1, 2, 3};

    if(testarr == {1, 2, 3}) {
        cout << "true" << endl;
    } else {
        cout << "false" << endl;
    }

    return 0;
}

That throws the compilation error:

||=== Build file: Debug in x(compiler: GNU GCC Compiler) ===|
C:\Users\x\Programming\C++\x\test.cpp||In function 'int main()':|
C:\Users\x\Programming\C++\x\test.cpp|11|error: expected primary-expression before '{' token|
C:\Users\x\Programming\C++\x\test.cpp|11|error: expected ')' before '{' token|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Do I have to make a new variable if I want to compare an std::array to another, only once used one?


Solution

  • Figured it out myself. You can do it by using the std::array class without making a new variable:

    #include<conio.h>
    #include<iostream>
    
    #include <array>
    
    using namespace std;
    
    int main() {
        std::array<short int, 3> testarr = {1, 2, 3};
    
        if(testarr == std::array<short int, 3>{1, 2, 3}) {
            cout << "true" << endl;
        } else {
            cout << "false" << endl;
        }
    
        return 0;
    }