Alan Valejo Alan Valejo - 11 months ago 58
C++ Question

Create fast a vector from in sequential values

How can I to create fast a vector from in sequential values


vector<int> vec (4, 100);
for (vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
cout << *it << endl;


# 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.

Answer Source

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;
int n(0);
std::generate_n(std::back_inserter(v), 100, [n]()mutable { return n++; });