[英]STL Algorithms to generate and copy a vector
Can you please tell me how to do the following using STL algorithms? 您能告诉我如何使用STL算法执行以下操作吗?
// Create a vector of 50 elements, and assign elem value same as index value
std::vector<int> a(50);
for (int i = 0; i < a.size(); i++)
{
a[i] = i;
}
// Create another vector by copying a section of vector a
std::vector<int> b;
size_t ind = 20;
b.resize(a.size() - ind);
for (int i = 0; i < b.size(); i++)
{
b[i] = a[i+ind];
}
Essentially, I am trying to create a new vector b, from vector a, by skipping the first 'ind' elements of a. 本质上,我试图通过跳过a的第一个“ ind”元素,从vector a创建一个新的vector b。
I'd probably do it something like this: 我可能会这样做:
std::vector<int> a(50);
// fill a with 0..N
std::iota(a.begin(), a.end(), 0);
size_t ind = 20;
// initialize `b` from elements of `a`:
std::vector<int> b{a.begin()+ind, a.end()};
You could use std::copy
for the second part, but for the case at hand I'd prefer to initialize b
from the iterators as I've done above. 您可以在第二部分中使用
std::copy
,但是对于手头的情况,我希望像上面所做的那样从迭代器中初始化b
。
With boost you could do the first part with initialization as well (see Jerry's answer). 通过boost,您也可以通过初始化完成第一部分(请参阅Jerry的答案)。
auto r = boost::irange(0,50);
auto a = std::vector<int>(std::begin(r), std::end(r));
Eric Neibler's range library I think includes this type of thing and I fully expect it'll make it into C++17. 我认为Eric Neibler的范围库包括这种类型的东西,我完全希望它将使它成为C ++ 17。 Until then you have to use his or boost's as a third-party lib.
在此之前,您必须使用他的或boost的第三方库。
Use the 使用
template <class InputIterator>
vector (InputIterator first, InputIterator last,
const allocator_type& alloc = allocator_type());
constructor as follows. 构造函数如下。
auto start = std::next(a.begin(), 20);
std::vector<int> b(start, a.end());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.