What's the best way for setting an std::vector<int>
to a range, e.g. all numbers between 3 and 16?
Slicing a Vector in C++ Method 1: The idea is to copy the elements from this range X to Y to a new vector and return it. Copy the elements in these range between these iterators using copy() function in vector.
The syntax for assigning values from an array or list: vectorname. assign(arr, arr + size) Parameters: arr - the array which is to be assigned to a vector size - number of elements from the beginning which has to be assigned.
You could use std::iota
if you have C++11 support or are using the STL:
std::vector<int> v(14);
std::iota(v.begin(), v.end(), 3);
or implement your own if not.
If you can use boost
, then a nice option is boost::irange
:
std::vector<int> v;
boost::push_back(v, boost::irange(3, 17));
std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
myVec.push_back( i );
See e.g. this question
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template<class OutputIterator, class Size, class Assignable>
void iota_n(OutputIterator first, Size n, Assignable value)
{
std::generate_n(first, n, [&value]() {
return value++;
});
}
int main()
{
std::vector<int> v; // no default init
v.reserve(14); // allocate 14 ints
iota_n(std::back_inserter(v), 14, 3); // fill them with 3...16
std::for_each(v.begin(), v.end(), [](int const& elem) {
std::cout << elem << "\n";
});
return 0;
}
Output on Ideone
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