Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create fast a vector from in sequential values

Tags:

c++

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.

like image 205
Alan Valejo Avatar asked Sep 04 '13 23:09

Alan Valejo


3 Answers

Here's another way...

int start = 27;
std::vector<int> v(100);
std::iota(v.begin(), v.end(), start);
like image 172
Retired Ninja Avatar answered Nov 15 '22 08:11

Retired Ninja


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++; });
like image 43
Dietmar Kühl Avatar answered Nov 15 '22 09:11

Dietmar Kühl


You want something like this:

std::vector<unsigned int> second(
    boost::counting_iterator<unsigned int>(0U),
    boost::counting_iterator<unsigned int>(99U));
like image 28
Paul Evans Avatar answered Nov 15 '22 10:11

Paul Evans