[英]c++ vector pushback slice of another vector in a concise way
I mean to build a vector of M N-sized-vectors, ie, with K=M*N total elements, from a K-sized vector with a linear arrangement of the same set of values.我的意思是从具有同一组值的线性排列的 K 大小的向量构建一个由 M 个 N 大小的向量组成的向量,即,具有 K=M*N 个总元素。 Moreover, I would do that in a class constructor, although I guess that is irrelevant.此外,我会在 class 构造函数中执行此操作,尽管我认为这无关紧要。 My code is shown below.我的代码如下所示。
What should I use in the pushback
line?我应该在pushback
线中使用什么?
template <int dim>
class vec2d {
public:
// Constructor - Version 1: 2D array as initializer
vec2d(const std::vector<std::vector<double> >& c);
// Constructor - Version 2: 1D array as initializer
vec2d(const std::vector<double>& c);
...
protected:
std::vector<std::vector<double> > _vec2d;
};
// Version 1: 2D array as initializer
...
// Version 2: 1D array as initializer
template <int dim>
vec2d::vec2d(const std::vector<double>& c)
{
for (size_t i = 0; i < (c.size() / dim); i++)
_vec2d.push_back(std::vector<double>(c(i * dim), c((i+1) * dim - 1))); // <- Fix this line
}
std::vector
has a constructor that takes an iterator range. std::vector
有一个构造函数,它采用迭代器范围。 Using that you can change you loop to use that like使用它,您可以更改循环以使用它
template <int dim>
vec2d::vec2d(const std::vector<double>& c)
{
auto begin = c.begin();
auto end = begin + dim;
for (size_t i = 0; i < (c.size() / dim); i++) {
_vec2d.emplace_back(begin, end);
begin += dim; // move range to next dim sized block
end += dim; // this could be moved into the for loops increment section
}
}
what about:关于什么:
template <int dim>
vec2d::vec2d(const std::vector<double>& c)
{
for (auto i = c.begin(); i < c.end(); i+=dim )
_vec2d.push_back({i, i+dim});
}
or mixing with the hint from @NathanOlivier:或与@NathanOlivier 的提示混合:
template <int dim>
vec2d::vec2d(const std::vector<double>& c)
{
for (auto i = c.begin(); i < c.end(); i+=dim )
_vec2d.emplace_back(i, i+dim);
}
we may debate if "emplace" is longer than "push" + "{}", but it should avoid a call to the move operator on the temporary vector passed as push_back()
argument.我们可能会争论“emplace”是否比“push”+“{}”长,但它应该避免在作为push_back()
参数传递的临时向量上调用移动运算符。
As pointed out, it assumes, based on your example that:正如所指出的,根据您的示例,它假设:
As optimization you should add _vec2d.resize(c.size()/dim)
or _vec2d.resize(dim)
before performing the series of invocation of the push_back()
method.作为优化,您应该在执行push_back()
方法的一系列调用之前添加_vec2d.resize(c.size()/dim)
或_vec2d.resize(dim)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.