Create fast vector from sequential values

How to create a fast vector from sequential values

For instance:.

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

Of:

 # 100 # 100 # 100 # 100 

I want to

 vector<int> vec (100, "0 to N"); 

I want to know the most effective way to achieve this result. For example, without using a loop.

N is a run-time variable.

+4
source share
6 answers

Here is a version that does not use a visible loop and only the standard C ++ library. This demonstrates well the use of lambda as a generator. Using 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++; }); 
+15
source

Here is another way ...

 int start = 27; std::vector<int> v(100); std::iota(v.begin(), v.end(), start); 
+19
source

You want something like this:

 std::vector<unsigned int> second( boost::counting_iterator<unsigned int>(0U), boost::counting_iterator<unsigned int>(99U)); 
+1
source

Using the generation 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; } 
+1
source
 const int num_seconds = 100; vector<int> second( num_seconds ); for( int n = 0 ; n < num_seconds ; ++n ) { second[ n ] = n; } 
0
source

I know this is an old question, but now I'm playing with library to deal with this particular problem. This requires C ++ 14.

 #include "htl.hpp" htl::Token _; std::vector<int> vec = _[0, _, 100]; // or for (auto const e: _[0, _, 100]) { ... } 
0
source

Source: https://habr.com/ru/post/1500626/


All Articles