在C ++中,如何创建一个元素从0到N的行向量? [英] How to create a row vector with elements from 0 up to and including N in C++?

查看:135
本文介绍了在C ++中,如何创建一个元素从0到N的行向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中创建一个行向量,该行向量具有从0到N的整数元素(我在C ++程序中分配的整数变量).我已经看过Armadillo C ++库并尝试使用其span函数,但是它没有创建矢量(而是创建了类型为arma::span的对象),因此编写:

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

不会创建所需的向量.如果有帮助(例如不清楚我对我想要什么的解释),我知道在MATLAB中这会创建我想要的向量:

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;

我并不在乎使用哪个库(如果有的话),只要该库在大多数主要的Linux发行版中都可用(例如我目前使用的Fedora 25).

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

推荐答案

您可以像这样使用std::iota.

#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';
    }
}

也许还有一种很酷的方法,可以在编译时使用std::integer_sequence和一些元编程.

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

这篇关于在C ++中,如何创建一个元素从0到N的行向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆