我想填写一个vector<int>
using std::fill
,但向量不应包含一个值,而是应包含按升序排列的数字。
我尝试通过将函数的第三个参数迭代 1 来实现此目的,但这只会给我填充 1 或 2 的向量(取决于++
操作员)。
Example:
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 http://en.cppreference.com/w/cpp/algorithm/iota像这样:
#include <vector>
#include <numeric>
// ...
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 http://en.cppreference.com/w/cpp/algorithm/generate像这样:
#include <vector>
#include <algorithm>
// ...
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)