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;
}
Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.
You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class. The array of size n is passed to the iterator constructor of the vector class.
Read a value into x , use that value as index into the vector, and increase the value at that index. So if the input for x is 1 , then it's equivalent to vec[1]++ , that is the second (remember that indexes are zero based) will be increased by one.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With