How can I to create fast a vector from in sequential values
Eg.:
vector<int> vec (4, 100);
for (vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
cout << *it << endl;
}
Out:
# 100
# 100
# 100
# 100
I want
vector<int> vec (100, "0 to N");
I want to know the most efficient way to achieve this result. For example, without using the loop.
N it a runtime variable.
Here's another way...
int start = 27;
std::vector<int> v(100);
std::iota(v.begin(), v.end(), start);
Here is a version not using a visible loop and only the standard C++ library. It nicely demonstrates the use of a lambda as generator, too. The use of reserve()
is optional and just intended to avoid more than one memory allocation.
std::vector<int> v;
v.reserve(100);
int n(0);
std::generate_n(std::back_inserter(v), 100, [n]()mutable { return n++; });
You want something like this:
std::vector<unsigned int> second(
boost::counting_iterator<unsigned int>(0U),
boost::counting_iterator<unsigned int>(99U));
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