生成和复制矢量的STL算法

STL Algorithms to generate and copy a vector

本文关键字:STL 算法 复制      更新时间:2023-10-16

你能告诉我如何使用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。

我可能会这样做:

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

使用boost,您也可以完成初始化的第一部分(请参阅Jerry的回答)。

auto r = boost::irange(0,50);
auto a = std::vector<int>(std::begin(r), std::end(r));

我认为Eric Neibler的范围库包含了这种类型的东西,我完全希望它能成为C++17。在此之前,您必须使用his或boost作为第三方库。

使用

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());