用步骤C ++构建向量 [英] Build a vector with step c++

查看:77
本文介绍了用步骤C ++构建向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不使用c ++的情况下以固定的步长将值从向量创建到另一个向量?

Is it possible to create a vector from a value to another one with a fixed step without using a loop in c++?

例如,我想用0.5步建立一个从1到10的向量.在MATLAB中,我可以按照以下步骤进行操作:

For example, I want to build a vector from 1 to 10 with step 0.5. In MATLAB I can do this as follow:

vector = [1:0.5:10];

在c ++中有类似的东西吗?

Is there something similar in c++?

推荐答案

您需要在某处循环.Matlab只是在向您隐藏循环.如果您经常这样做,则只需创建一个函数以使其易于使用即可:

You need a loop somewhere. Matlab is simply hiding the loop from you. If this is something you do often, just create a function to make it easier to use:

#include <vector>

auto make_vector(double beg, double step, double end) 
{
    std::vector<double> vec;
    vec.reserve((end - beg) / step + 1);
    while (beg <= end) {
        vec.push_back(beg);
        beg += step;
    }
    return vec;
}

int main() {
    auto vec = make_vector(1, 0.5, 10);
}

这篇关于用步骤C ++构建向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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