Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set std::vector<int> to a range

What's the best way for setting an std::vector<int> to a range, e.g. all numbers between 3 and 16?

like image 377
Andreas Avatar asked Aug 15 '12 07:08

Andreas


People also ask

How do you pass a range of a vector in C++?

Slicing a Vector in C++ Method 1: The idea is to copy the elements from this range X to Y to a new vector and return it. Copy the elements in these range between these iterators using copy() function in vector.

How do you assign a value to a vector INT?

The syntax for assigning values from an array or list: vectorname. assign(arr, arr + size) Parameters: arr - the array which is to be assigned to a vector size - number of elements from the beginning which has to be assigned.


3 Answers

You could use std::iota if you have C++11 support or are using the STL:

std::vector<int> v(14);
std::iota(v.begin(), v.end(), 3);

or implement your own if not.

If you can use boost, then a nice option is boost::irange:

std::vector<int> v;
boost::push_back(v, boost::irange(3, 17));
like image 192
juanchopanza Avatar answered Oct 17 '22 03:10

juanchopanza


std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
    myVec.push_back( i );
like image 30
SingerOfTheFall Avatar answered Oct 17 '22 03:10

SingerOfTheFall


See e.g. this question

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

template<class OutputIterator, class Size, class Assignable>
void iota_n(OutputIterator first, Size n, Assignable value)
{
        std::generate_n(first, n, [&value]() {
                return value++;
        });
}

int main()
{
    std::vector<int> v;                   // no default init
    v.reserve(14);                        // allocate 14 ints
    iota_n(std::back_inserter(v), 14, 3); // fill them with 3...16

    std::for_each(v.begin(), v.end(), [](int const& elem) {
        std::cout << elem << "\n";
    });
    return 0;
}

Output on Ideone

like image 8
TemplateRex Avatar answered Oct 17 '22 03:10

TemplateRex