c++arraysstd-pair

why std::pair<int[N], int[N]> is not allowed in C++?


Why the C++ code below can't be compiled?

#include <utility>

int main() {
    int x[6];
    int y[6];
    std::pair<int[6], int[6]> a(x, y);
    return 0;
}

For example MSVC gives the following error:

error C2661: 'std::pair<int [6],int [6]>::pair': no overloaded function takes 2 argument

Thanks for the comments that using C++ alternatives to construct arrays, but I also want to know the reason that the code can't be compiled.


Solution

  • Using int[] as a type of element in a std::pair is actually allowed.
    For example you could use:

    std::pair<int[6], int[6]> a;
    a.first[0] = 1;
    

    What's not valid is the initialization of the pair with (x,y). C arrays are not copy assignable: you cannot assign some array a2 to another a1 by the trivial assignment a1 = a2;. And C arrays decay into pointers when passed to a funtion/method.

    However, the prefered way to do it in C++ is to use std::array:

    #include <utility>
    #include <array>
    
    using IntArr6 = std::array<int, 6>;
    IntArr6 x{ 1,2,3,4,5,6 };
    IntArr6 y{ 11,22,33,44,55,66 };
    std::pair<IntArr6, IntArr6> aa{ x,y };
    

    Note the usage of using (providing a type alias) to make the code more readable.