Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to initialize a vector with increasing values in a single line?

Is it possible to merge the two initialization lines into a single statement with the help of initializer lists or other C++ features? The vector values always increment with one, but the size n is not fixed.

#include <numeric>
#include <vector>
#include <iostream>

int main()
{
    int n = 10;

    // Can the two lines below be combined into a single statement?
    std::vector<int> v(n);
    std::iota(v.begin(), v.end(), 1);

    for (int i : v)
        std::cout << i << std::endl;

    return 0;
}
like image 708
Chiel Avatar asked Apr 18 '16 15:04

Chiel


People also ask

What is the correct way to initialize vector?

Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.

Is it possible to initialize any vector with an array in C++?

You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class. The array of size n is passed to the iterator constructor of the vector class.

How do you increment a vector value?

Read a value into x , use that value as index into the vector, and increase the value at that index. So if the input for x is 1 , then it's equivalent to vec[1]++ , that is the second (remember that indexes are zero based) will be increased by one.


2 Answers

You can use Boost.counting_iterator for this:

std::vector<int> v(boost::counting_iterator<int>(1),
                    boost::counting_iterator<int>(n + 1));

(Live) Now whether this is worth it and easier to read than what you already have is for you to decide.

like image 159
Baum mit Augen Avatar answered Oct 19 '22 06:10

Baum mit Augen


Not really, no. If n is a runtime variable, the best you could probably do is to just throw this in a function somewhere:

std::vector<int> ints(int n) {
    std::vector<int> v;
    v.reserve(n);
    for (int i = 0; i < n; ++i) {
        v.push_back(n+1);
    }
    return v;
}

// now it's one line?
std::vector<int> v = ints(n);

If it's compile time, you can use std::index_sequence to provide an initializer list:

template <int... Is>
std::vector<int> ints(std::integer_sequence<int, Is...> ) {
    return std::vector<int>{ (Is+1)... };
}


template <int N>
std::vector<int> ints() {
    return ints(std::make_integer_sequence<int, N>{});
}

But either way, you need a helper function.

like image 29
Barry Avatar answered Oct 19 '22 07:10

Barry