简体   繁体   English

如何用两个点和步骤之间的元素初始化向量C ++

[英]How to initialize a vector with elements between two point and step c++

I'm going to initialize a vector that the elements are scaled uniformly between two numbers with known steps. 我将初始化一个向量,该向量以已知的步长在两个数字之间均匀缩放。 something like this pseudo code. 像这样的伪代码。

typedef vector<double> a(startnumber, step, endnumber);

eg 例如

vector<double> a(1, 1, 10); // a = {1, 2, ...., 10};

Is there any way to do it in c++? 有什么办法可以在C ++中做到吗?

Sure: 当然:

template <typename T>
std::vector<T> createRange(T start, T end, T step)
{
    std::vector<T> result;
    for (; start < end; start += step) {
        result.push_back(start);
    }
    return result;
}

Anything else is more complicated without really being better (eg something with iota() or generate() ). 其他任何事情在没有真正变得更好的情况下都更加复杂(例如,使用iota()generate() )。 This'll only work if step > 0. If you want it to work for negative steps, will have to switch on the sign to check start > end in that case instead. 这仅在step > 0时有效。如果您希望它对负步起作用,则在这种情况下,必须打开标志以检查start > end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM