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

2.1k Views Asked by At

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.

4

There are 4 best solutions below

0
On BEST ANSWER

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);
1
On

As an alternative, as you explicitly state that std::array is not to be used, you could use pointers, it's kind of an oddball solution but it would work:

#include <iostream>
#include <vector>

int main()
{
    const int SIZE = 2;
    std::vector<int*> v;
    static int p[SIZE] = {1, 2}; //extended lifetime, static storage duration
    int *ptr[SIZE]; //array of pointers, one for each member of the array

    for(int i = 0; i < SIZE; i++){
        ptr[i] = &p[i];  //assign pointers
    }
 
    v.push_back(*ptr); //insert pointer to the beginning of ptr

    for(auto& n : v){
        for(int i = 0; i < SIZE; i++){ 
            std::cout << n[i] << " "; //output: 1 2
        }
    }
}
5
On

Use std::array:

vector<std::array<int, 2>> v;
std::array<int, 2> p = {1, 2};
v.push_back(p);
4
On

I think you should check the C++ reference for vectors.

http://www.cplusplus.com/reference/vector/vector/vector/

You can see in the example, there is explained every way you can initialize a vector.

I think that for your case you need to do:

 std::vector<int> v({ 1, 2 });
 v.push_back(3);