How can I do the equivalent of the following using C++/STL? I want to fill a std::vector
with a range of values [min, max).
# Python
>>>
I don't know of a way to do it like in python but another alternative is obviously to for loop through it:
for (int i = range1; i < range2; ++i) {
x.push_back(i);
}
chris's answer is better though if you have c++11
In C++11, there's std::iota
:
#include <vector>
#include <numeric> //std::iota
std::vector<int> x(10);
std::iota(std::begin(x), std::end(x), 0); //0 is the starting number
If you can't use C++11, you can use std::partial_sum
to generate numbers from 1 to 10. And if you need numbers from 0 to 9, you can then subtract 1 using transform:
std::vector<int> my_data( 10, 1 );
std::partial_sum( my_data.begin(), my_data.end(), my_data.begin() );
std::transform(my_data.begin(), my_data.end(), my_data.begin(), bind2nd(std::minus<int>(), 1));
For those who can't use C++11 or libraries:
vector<int> x(10,0); // 0 is the starting number, 10 is the range size
transform(x.begin(),x.end(),++x.begin(),bind2nd(plus<int>(),1)); // 1 is the increment