是否可以在单行中初始化具有增加值的向量? [英] Is it possible to initialize a vector with increasing values in a single line?
本文介绍了是否可以在单行中初始化具有增加值的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有可能在初始化列表或其他C ++功能的帮助下将两个初始化行合并成一个语句吗?向量值总是递增1,但大小 n
不固定。
Is it possible to merge the two initialization lines into a single statement with the help of initializer lists or other C++ features? The vector values always increment with one, but the size n
is not fixed.
#include <numeric>
#include <vector>
#include <iostream>
int main()
{
int n = 10;
// Can the two lines below be combined into a single statement?
std::vector<int> v(n);
std::iota(v.begin(), v.end(), 1);
for (int i : v)
std::cout << i << std::endl;
return 0;
}
推荐答案
=http://www.boost.org/doc/libs/release/libs/iterator/doc/counting_iterator.html> Boost.counting_iterator :
You can use Boost.counting_iterator for this:
std::vector<int> v(boost::counting_iterator<int>(1),
boost::counting_iterator<int>(n + 1));
( Live )现在这是否值得,并且比你已经有的更容易阅读,这是你决定。
(Live) Now whether this is worth it and easier to read than what you already have is for you to decide.
这篇关于是否可以在单行中初始化具有增加值的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文