生成和复制矢量的STL算法
STL Algorithms to generate and copy a vector
你能告诉我如何使用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());
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- STL算法函数在多个一维容器上的使用
- C++:尝试使用等效的 STL 算法消除原始循环
- STL算法和back_inserter可以预分配空间吗?
- 如何使用 STL 算法将整数向量转换为字符串向量?
- 是否有一种 STL 算法可以最后找到,但它也适用于指针?
- C++ - 如何使用<int> <int>STL 算法功能在矢量<vector>中找到矢量?
- 如何在变量容器上使用stl算法
- 在 stl 算法中移动迭代器
- 如何使用 STL 算法找到最小值和最大值?
- C STL算法相等
- 在 stl 算法中使用函数对象
- 重新定义要在字符串的 STL 算法中使用的<运算符
- 将 STL 算法与 Qt 容器结合使用
- 使用STL算法合并2个向量
- STL算法函数,如累加,如果传递给它们的函数接受引用,请避免复制
- 什么 STL 算法可以确定容器中的一个项目是否满足谓词?
- c ++ 是否有 STL 算法来检查范围是否严格排序
- begin() 和 end() 用于 STL 算法
- STL算法并嵌套以循环