0

I would like to create a row vector in C++ with integer elements from and including 0 to N (an integer variable I assign in my C++ program). I have seen the Armadillo C++ library and tried using its span function but it does not create a vector (rather creates an object with type arma::span) so writing:

vec n = span(0,N);

does not create the desired vector. If it helps (like if my explanation of what I want is unclear) I know that in MATLAB this creates the vector I want:

n=0:N;

I do not really care which library (if any) is used, provided the library is available on most major Linux distributions (like my present one, Fedora 25).

Josh Pinto
  • 1,453
  • 4
  • 20
  • 37
  • 2
    Can you give an example of your required output. Is it just a vector like {0,1,2,3,4,5,6,7,8,9}, where N=9? If so maybe [`std::iota`](http://en.cppreference.com/w/cpp/algorithm/iota)? – Paul Rooney Dec 08 '16 at 02:02
  • Yeah, just a vector nothing special, just like you described in your example. – Josh Pinto Dec 08 '16 at 02:04
  • OK, well if you can show me how I can use `std::iota` to create a vector `n` with elements of (and including) `0` to `N` I'll accept your answer. – Josh Pinto Dec 08 '16 at 02:09
  • [Create fast a vector from in sequential values](http://stackoverflow.com/q/18625223/995714) – phuclv Dec 08 '16 at 04:07

2 Answers2

2

You could use std::iota like so.

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

int main()
{
    int N = 9;
    std::vector<int> n(N + 1);
    std::iota(begin(n), end(n), 0);

    for(auto i: n)
    {
        std::cout << i << '\n';
    }
}

Theres probably also a cool way to do it at compile time using std::integer_sequence and some metaprogramming.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
1

You can use the function std::iota like this:

std::vector<int> v(n + 1);
std::iota(v.begin(), v.end(), 0);

Or you could wrap that up into a function like this:

inline std::vector<int> zero_to_n_vector(std::size_t n)
{
    std::vector<int> v(n + 1);
    std::iota(v.begin(), v.end(), 0);
    return v;
}

auto v = zero_to_n_vector(20);
Galik
  • 47,303
  • 4
  • 80
  • 117