NirMH
NirMH

Reputation: 4929

Is there a simple / elegant way to push a Range of integers to an STD vector?

I have a simple task which is to initialize an std::vector<int> with a range of integers.

The range is given by the user, and i try to avoid using a for loop.

Something like:

void addRange(std::vector<int>& vReturn, int nStart, int nEnd)
{
    vReturn.clear();

    // straightforward solution
    for (int nInteger = nStart; nInteger <= nEnd; nInteger++)
    {
         vReturn.push_back(nInteger);
    }
    //////////////////////////////////////////////

    // Elegent Pseudo-Code
    vReturn.add_range(nStart, nEnd);   // <<- is this doable?

}

Upvotes: 3

Views: 916

Answers (2)

Nik
Nik

Reputation: 1334

I have an alternative solution and it does not use for loop and does not use boost or C++11


#include <iostream>
#include <vector>

using namespace std;

struct Add{

  void operator()(int x, int y, vector<int>& vec)
  {
    if(x > y)
      return;

    vec.push_back(x);
    operator()(++x, y, vec);
  }
};

void addRange(std::vector<int>& vReturn, const int nStart, const int nEnd)
{
   vReturn.resize(nEnd - nStart); 
   vReturn.clear(); 
   Add()(nStart, nEnd, vReturn);  //update the vector using Functor object
}

int main()
{
   vector<int> vec;
   int start = 1, end = 10;

   addRange(vec, start , end);


   return 0;
}

Upvotes: 0

ForEveR
ForEveR

Reputation: 55887

You can do this in C++11, using algorithm iota.

vReturn.clear();
vReturn.resize((nEnd - nStart) + 1);
std::iota(vReturn.begin(), vReturn.end(), nStart);

You can also use boost::irange.

auto range = boost::irange<int>(nStart, nEnd + 1);
vReturn.assign(range.begin(), range.end());

Upvotes: 9

Related Questions