首页 > 解决方案 > 如何 push_back() C 数组到 std::vector

问题描述

这不编译:

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

https://godbolt.org/z/Kabq8Y

有什么选择?我不想使用std::array.

自己的std::vector声明编译。这是push_back不编译的。

标签: c++arraysstdvectorpush-back

解决方案


如果您真的不想使用,可以使用包含数组的结构或包含两个整数的结构std::array

struct coords {
    int x, y;
};

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

或者,如前所述,您可以使用包含数组的结构:

struct coords {
    int x[2];
};

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

推荐阅读