Reputation: 1315
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.
Upvotes: 5
Views: 6796
Reputation: 643
I know this is old question, but I am currently playing with library to handle exactly this problem. It requires c++14.
#include "htl.hpp"
htl::Token _;
std::vector<int> vec = _[0, _, 100];
// or
for (auto const e: _[0, _, 100]) { ... }
Upvotes: 0
Reputation: 154005
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++; });
Upvotes: 17
Reputation: 4925
Here's another way...
int start = 27;
std::vector<int> v(100);
std::iota(v.begin(), v.end(), start);
Upvotes: 23
Reputation: 296
Using the generate algorithm :
#include <iostream> // std::cout
#include <algorithm> // std::generate
#include <vector> // std::vector
#include <iterator>
// function generator:
struct one_more {
int _count;
one_more() : _count(0) {}
int operator()() {
return _count++;
}
};
int main () {
std::vector<int> myvector (100);
std::generate (myvector.begin(), myvector.end(), one_more());
std::copy(myvector.begin(), myvector.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
Upvotes: 1
Reputation: 5939
const int num_seconds = 100;
vector<int> second( num_seconds );
for( int n = 0 ; n < num_seconds ; ++n ) {
second[ n ] = n;
}
Upvotes: 0
Reputation: 27577
You want something like this:
std::vector<unsigned int> second(
boost::counting_iterator<unsigned int>(0U),
boost::counting_iterator<unsigned int>(99U));
Upvotes: 2