use std::fill to populate vector with increasing numbers(使用 std::fill 填充带有递增数字的向量)
问题描述
我想用 std::fill
填充一个 vector
,但不是一个值,该向量应该包含后面按升序排列的数字.
I would like to fill a vector<int>
using std::fill
, but instead of one value, the vector should contain numbers in increasing order after.
我尝试通过将函数的第三个参数迭代 1 来实现这一点,但这只会给我填充 1 或 2 的向量(取决于 ++
运算符的位置).
I tried achieving this by iterating the third parameter of the function by one, but this would only give me either vectors filled with 1 or 2 (depending of the position of the ++
operator).
示例:
vector<int> ivec;
int i = 0;
std::fill(ivec.begin(), ivec.end(), i++); // elements are set to 1
std::fill(ivec.begin(), ivec.end(), ++i); // elements are set to 2
推荐答案
最好使用 std::iota
像这样:
Preferably use std::iota
like this:
std::vector<int> v(100) ; // vector with 100 ints.
std::iota (std::begin(v), std::end(v), 0); // Fill with 0, 1, ..., 99.
也就是说,如果您没有任何 c++11
支持(仍然是我工作的真正问题),请使用 std::generate
像这样:
That said, if you don't have any c++11
support (still a real problem where I work), use std::generate
like this:
struct IncGenerator {
int current_;
IncGenerator (int start) : current_(start) {}
int operator() () { return current_++; }
};
// ...
std::vector<int> v(100) ; // vector with 100 ints.
IncGenerator g (0);
std::generate( v.begin(), v.end(), g); // Fill with the result of calling g() repeatedly.
这篇关于使用 std::fill 填充带有递增数字的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 std::fill 填充带有递增数字的向量


- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01