C++之创建等间隔数组

在 C++ 中,数组是一种基本的数据结构,用于存储固定大小的相同类型的元素。数组在声明时必须指定其大小,并且一旦创建,其大小就不可改变。数组的索引从 0 开始。

复制代码
int myArray[5]; // 声明一个整型数组,包含5个元素int anotherArray[5] = {1, 2, 3, 4, 5}; // 声明并初始化一个整型数组

虽然传统的 C++ 数组在声明时大小固定,但 C++ 标准库提供了 std::vector 类,它是一个动态数组,可以在运行时调整大小。

复制代码
#include <vector>std::vector<int> myVector; // 声明一个动态数组myVector.push_back(10); // 添加元素

在 C++ 中,没有内置的函数直接对应于 NumPy 的 linspace 或 arange,但可以通过结合使用标准库中的函数来实现类似的功能。以下是两种方法:

1. 使用 std::vector 和循环来创建等间隔的数组(类似 linspace)

复制代码
#include <iostream>#include <vector>#include <algorithm> // for std::transform​std::vector<double> linspace(double start, double end, int num) {    std::vector<double> linspaced;    if (num == 0) { return linspaced; }    if (num == 1) { linspaced.push_back(start); return linspaced; }    double delta = (end - start) / (num - 1);    linspaced.push_back(start);    std::generate_n(std::back_inserter(linspaced), num - 1, [&]() {        double next = start + delta;        delta = (end - start) / (num - 1);        start = next;        return next;    });    linspaced.push_back(end); // Ensure the end is included    return linspaced;}​int main() {    auto vec = linspace(0, 1, 5);    for (auto v : vec) {        std::cout << v << " ";    }    std::cout << std::endl;    return 0;}

2. 使用 std::vector 和 std::iota 来创建一个序列(类似 arange)

在 C++11 之前,std::iota 是定义在 <algorithm> 头文件中的,但 C++11 之后,它被移到了 <numeric>。

复制代码
#include <iostream>#include <vector>#include <numeric> // for std::iota​std::vector<int> arange(int start, int end, int step) {    std::vector<int> range;    range.reserve((end - start) / step + 1); // 预分配足够的空间    int value = start;    while (value < end) {        range.push_back(value);        value += step;    }    return range;}​int main() {    auto vec = arange(0, 10, 2);    for (auto v : vec) {        std::cout << v << " ";    }    std::cout << std::endl;    return 0;}

补充:

  • **np.linspace(start, stop, num):**返回一个从 start 开始到 stop 结束的等间隔数字的数组,包括结束值,总共 num 个数字。

  • **np.arange(start, stop, step):**返回一个从 start 开始到 stop 结束(不包括 stop),以 step 为步长的等间隔数字的数组。

相关推荐
rainFFrain29 分钟前
Boost搜索引擎项目(详细思路版)
网络·c++·http·搜索引擎
long_run1 小时前
C++之模板函数
c++
NuyoahC1 小时前
笔试——Day43
c++·算法·笔试
彷徨而立2 小时前
【C++】 using声明 与 using指示
开发语言·c++
一只鲲2 小时前
48 C++ STL模板库17-容器9-关联容器-映射(map)多重映射(multimap)
开发语言·c++
智践行3 小时前
C++11 智能指针:`std::unique_ptr`、`std::shared_ptr`和`std::weak_ptr`
c++
智践行3 小时前
C++11之后的 Lambda 表达式 以及 `std::function`和`std::bind`
c++
智践行3 小时前
C++11移动语义‘偷梁换柱’实战
c++
祁同伟.4 小时前
【C++】模版(初阶)
c++
sTone873755 小时前
android studio之外使用NDK编译生成android指定架构的动态库
android·c++