如何将 push_back() C 数组转换为 std::vector
How to push_back() C array into std::vector
这不编译:
vector<int[2]> v;
int p[2] = {1, 2};
v.push_back(p); //< compile error here
还有什么选择? 我不想用std::array
.
std::vector
自身声明编译。是 push_back
无法编译。
作为替代方案,当您明确声明不使用 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
}
}
}
使用std::array
:
vector<std::array<int, 2>> v;
std::array<int, 2> p = {1, 2};
v.push_back(p);
我认为你应该查看向量的 C++ 参考。
http://www.cplusplus.com/reference/vector/vector/vector/
您可以在示例中看到,对可以初始化向量的每种方式进行了说明。
我认为对于你的情况你需要做:
std::vector<int> v({ 1, 2 });
v.push_back(3);
如果您真的不想使用std::array
:[=13=,您可以使用包含数组的结构或包含两个整数的结构]
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);
这不编译:
vector<int[2]> v;
int p[2] = {1, 2};
v.push_back(p); //< compile error here
还有什么选择? 我不想用std::array
.
std::vector
自身声明编译。是 push_back
无法编译。
作为替代方案,当您明确声明不使用 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
}
}
}
使用std::array
:
vector<std::array<int, 2>> v;
std::array<int, 2> p = {1, 2};
v.push_back(p);
我认为你应该查看向量的 C++ 参考。
http://www.cplusplus.com/reference/vector/vector/vector/
您可以在示例中看到,对可以初始化向量的每种方式进行了说明。
我认为对于你的情况你需要做:
std::vector<int> v({ 1, 2 });
v.push_back(3);
如果您真的不想使用std::array
:[=13=,您可以使用包含数组的结构或包含两个整数的结构]
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);