How to create a row vector with elements from 0 up to and including N in C++? [duplicate]

送分小仙女□ 提交于 2019-12-25 08:38:16

问题


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).


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/41030499/how-to-create-a-row-vector-with-elements-from-0-up-to-and-including-n-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!