Alan Valejo Alan Valejo - 1 month ago 5
C++ Question

Create fast a vector from in sequential values

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.

Answer

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++; });
Comments