[英]How can I push_back/copy custom type ( array) object to vector?
Here is a fragment of my code in which I declare foo:这是我声明 foo 的代码片段:
typedef pair<a, b> foo[8][8];
I wrote a function that copies objects of this type:我写了一个 function 来复制这种类型的对象:
copy(foo1, foo2);
will copy foo2 to foo1.将 foo2 复制到 foo1。 foo1 and foo2 are of type foo. foo1 和 foo2 是 foo 类型。 Also, I have this vector:另外,我有这个向量:
vector<foo> lst;
I would like to have convenient access to it, ie lst [0][0][0].first
would be an object of type a.我想方便地访问它,即lst [0][0][0].first
.first 将是 a 类型的 object。 How can I copy a foo object to this vector (lst)?如何将 foo object 复制到此向量(lst)? I tried to do it this way:我试着这样做:
lst.push_back( new foo );
copy(lst[lst.size() - 1], foo1);
How can I do such a thing?我怎么能做这样的事情?
std::vector<foo>
means "vector of foo values", you can't push_back(new foo)
into it as new foo
is a pointer ( foo*
). std::vector<foo>
意思是“foo 值的向量”,你不能push_back(new foo)
因为new foo
是一个指针( foo*
)。 You'd need to push_back(foo{})
which default-constructs a foo
instance (a value).您需要push_back(foo{})
,它默认构造一个foo
实例(一个值)。 This doesn't work because:这不起作用,因为:
std::vector<T>::push_back
requires that T
is MoveInsertable (in this particular case) std::vector<T>::push_back
要求T
是MoveInsertable (在这种特殊情况下)foo
is a C-array, and C-arrays are not MoveInsertable foo
是一个 C 数组,而 C 数组不是MoveInsertable In general, C-arrays don't work well with std::vector
.通常,C 数组不适用于std::vector
。 You can use std::array
instead, because it is MoveInsertable .您可以改用std::array
,因为它是MoveInsertable 。
#include <vector>
#include <array>
#include <iostream>
using foo = std::array<std::array<std::pair<float, float>, 8>, 8>;
std::vector<foo> v;
v.push_back(foo{});
std::cout << v[0][0][0].first << "\n";
In this case you don't need your copy
function as std::array
will do copying在这种情况下,您不需要您的copy
function 因为std::array
会进行复制
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.