问题
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;
}
回答1:
You can use Boost.counting_iterator for this:
std::vector<int> v(boost::counting_iterator<int>(1),
boost::counting_iterator<int>(n + 1));
(Live) Now whether this is worth it and easier to read than what you already have is for you to decide.
回答2:
Not really, no. If n
is a runtime variable, the best you could probably do is to just throw this in a function somewhere:
std::vector<int> ints(int n) {
std::vector<int> v;
v.reserve(n);
for (int i = 0; i < n; ++i) {
v.push_back(n+1);
}
return v;
}
// now it's one line?
std::vector<int> v = ints(n);
If it's compile time, you can use std::index_sequence
to provide an initializer list:
template <int... Is>
std::vector<int> ints(std::integer_sequence<int, Is...> ) {
return std::vector<int>{ (Is+1)... };
}
template <int N>
std::vector<int> ints() {
return ints(std::make_integer_sequence<int, N>{});
}
But either way, you need a helper function.
来源:https://stackoverflow.com/questions/36697980/is-it-possible-to-initialize-a-vector-with-increasing-values-in-a-single-line