问题描述
无法编译:
vector<int[2]> v;
int p[2] = {1,2};
v.push_back(p); //< compile error here
有什么选择? 我不想使用std::array
。
std::vector
声明本身会编译。是push_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);
,
使用std::array
:
vector<std::array<int,2>> v;
std::array<int,2> p = {1,2};
v.push_back(p);
,
作为替代方案,正如您明确声明不使用std::array
一样,您可以使用指针,这是一种奇怪的解决方案,但可以使用:
#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
}
}
}
,
我认为您应该检查C ++参考中的向量。
http://www.cplusplus.com/reference/vector/vector/vector/
您可以在示例中看到,其中解释了初始化向量的每种方法。
我认为对于您的情况,您需要这样做:
std::vector<int> v({ 1,2 });
v.push_back(3);