Compare arrays in C++

Viewed 84

I'm having some issues comparing two arrays:

int array[3] = {23, 14, 1};

if (array == {12, 43, 1}) {
    // Do something
}

The error I get is:

error: expected primary-expression before '{' token

       if (array == {12, 43, 1}) {

                        ^

error: expected ')' before '{' token

I also tried this:

bool compareArrays(int firstArray[], int secondArray[], int length) {
    for (int i = 0; i < length; i++) {
        if (firstArray[i] != secondArray[i]) {
            return false;
        }
    }

    return true;
}

But I get another error when I do so:

if (compareArrays(array, {12, 43, 1}, 3)) {
    // Do something
}

error: cannot convert '<brace-enclosed initializer list>' to 'int*' for argument '2' to 'bool compareArrays(int*, int*, int)'

How can I solve the problem ? Thanks in advance.

3 Answers

This declaration:

bool compareArrays(int firstArray[], int secondArray[], int length) {

accepts pointers to ints. But you can't decay a brace-init list to a pointer.

Instead, the function can accept fixed-size arrays, and compare them with an algorithm:

template<size_t N>
bool compareArrays(int (&firstArray)[N], int (&secondArray)[N]) {
  return std::equal(std::begin(firstArray),std::end(firstArray),
                    std::begin(secondArray));
}

Note that you no longer need to pass length as the function will deduce it.

You can use std::array. With C++20 it's as simple as

#include <array>

int main() {
    int array[3] = {23, 14, 1};

    if (std::to_array(array) == std::array{12, 43, 1}) {
    // Do something
    }
}

Or with C++17

#include <array>

int main() {
    std::array array = {23, 14, 1};

    if (array == std::array{12, 43, 1}) {
    // Do something
    }
}

Just another suggestion. You can use std::memcmp to compare arrays whose elements are ints or other PODs.

Related