(C++) GetIncVector

January 25, 2018 · View on GitHub

 

 

 

 

 

(C++) GetIncVector

 

GetIncVector is a std::vector code snippet to obtain a std::vector with incremented values, for example, with values 0,1,2,3,etc.

 

There are multiple versions of GetIncVector:

 

 

 

 

 

Using C++11 std::iota

 

std::iota is in the C++11 STL and can be found in the header file algorithm.h.

 


#include <algorithm> #include <iostream> #include <iterator> #include <vector> int main() {   //Create a std::vector consisting of ten zeroes   std::vector<int> v(10,0);   //Let iota assign incrementing values to the std::vector,   //starting from zero   std::iota(v.begin(),v.end(),0);   //Show the std::vector   std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout," ")); }

 

Screen output:

 


0 1 2 3 4 5 6 7 8 9

 

 

 

 

 

Using C++98 custom iota

 

iota was not among the C++98 STL. Below the code shown an implementation and example of it.

 


 

Screen output:

 


0 1 2 3 4 5 6 7 8 9

 

 

 

 

 

Using a custom functor

 


#include <algorithm> #include <iostream> #include <iterator> #include <vector> //From http://www.richelbilderbeek.nl/CppFunctorIncrease.htm struct Increase : public std::unary_function<void,int> {   explicit Increase(const int initValue = 0) : mValue(initValue) {}   void operator()(int& anything)   {     anything = mValue;     ++mValue;   }   private:   int mValue; }; //From http://www.richelbilderbeek.nl/CppGetIncVector.htm const std::vector<int> GetIncVector(const std::size_t sz, const int init_val = 0) {   std::vector<int> v(sz,0);   std::for_each(v.begin(),v.end(),Increase(init_val));   return v; } //From http://www.richelbilderbeek.nl/CppCoutContainer.htm template <class Container> void CoutContainer(const Container& c) {   std::copy(c.begin(),c.end(),     std::ostream_iterator<typename Container::value_type>(std::cout,"\n")); } int main() {   const std::size_t sz = 5;   const std::vector<int> v = GetIncVector(sz);   CoutContainer(v); }