Search code examples
c++arraysstdvectorpush-back

How to push_back() C array into std::vector


This doesn't compile:

vector<int[2]> v;
int p[2] = {1, 2};
v.push_back(p); //< compile error here

https://godbolt.org/z/Kabq8Y

What's the alternative? I don't want to use std::array.

The std::vector declaration on itself compiles. It's the push_back that doesn't compile.


Solution

  • You could use a structure containing an array, or a structure containing two integers, if you really don't want to use std::array:

    struct coords {
        int x, y;
    };
    
    vector<coords> v;
    coords c = {1, 2};
    v.push_back(c);
    

    alternatively, as mentioned, you could use a structure containing an array:

    struct coords {
        int x[2];
    };
    
    vector<coords> v;
    coords c = {1, 2};
    v.push_back(c);