请告诉我如何使用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];
}
基本上,我试图通过跳过a的第一个“ind”元素,从矢量a创建一个新的矢量b。
答案 0 :(得分:8)
我可能会这样做:
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()};
您可以使用std::copy
作为第二部分,但对于手头的情况,我更倾向于从迭代器初始化b
,如上所述。
答案 1 :(得分:1)
通过提升,您可以在初始化时完成第一部分(参见Jerry的回答)。
auto r = boost::irange(0,50);
auto a = std::vector<int>(std::begin(r), std::end(r));
我认为Eric Neibler的范围库包含了这种类型的东西,我完全相信它会进入C ++ 17。在那之前,你必须使用他或者作为第三方的lib。
答案 2 :(得分:0)
使用
template <class InputIterator>
vector (InputIterator first, InputIterator last,
const allocator_type& alloc = allocator_type());
构造函数如下。
auto start = std::next(a.begin(), 20);
std::vector<int> b(start, a.end());