「C/C++」C/C++STL篇 之 数组赋值给std::vector多种方法

✨博客主页
何曾参静谧的博客
「C/C++」C/C++程序设计
「VS」Visual Studio 「C/C++」C/C++程序设计 「UG/NX」BlockUI集合
「Win」Windows程序设计 「DSA」数据结构与算法 「UG/NX」NX二次开发
「QT」QT5程序设计 「File」数据文件格式 「PK」Parasolid函数说明

目录

      • 方法一:使用构造函数
      • [方法二:使用 `std::copy`](#方法二:使用 std::copy)
      • [方法三:使用范围构造器(C++11 及以上)](#方法三:使用范围构造器(C++11 及以上))
      • [方法四:使用 `std::array` 作为中间步骤(如果数组大小固定)](#方法四:使用 std::array 作为中间步骤(如果数组大小固定))

要将一个双精度浮点数数组(如 double mtx[16])传递给一个 std::vector<double>,你可以使用以下几种方法:

方法一:使用构造函数

std::vector 提供了一个可以接受数组和数组大小的构造函数,因此你可以直接将数组的内容复制到 std::vector 中。

cpp 复制代码
#include <vector>
#include <iostream>

int main() {
    double mtx[16] = { /* 初始化你的数组 */ };

    // 使用数组和数组大小来构造vector
    std::vector<double> vec(mtx, mtx + 16);

    // 输出验证
    for (double val : vec) {
        std::cout << val << " ";
    }
    std::cout << std::endl;

    return 0;
}

方法二:使用 std::copy

你也可以使用标准库中的 std::copy 函数将数组内容复制到 std::vector 中。

cpp 复制代码
#include <vector>
#include <algorithm> // for std::copy
#include <iostream>

int main() {
    double mtx[16] = { /* 初始化你的数组 */ };

    // 创建一个大小适当的vector
    std::vector<double> vec(16);

    // 使用std::copy将数组内容复制到vector中
    std::copy(mtx, mtx + 16, vec.begin());

    // 输出验证
    for (double val : vec) {
        std::cout << val << " ";
    }
    std::cout << std::endl;

    return 0;
}

方法三:使用范围构造器(C++11 及以上)

在 C++11 及以后的版本中,你可以使用列表初始化来手动构造 std::vector,不过这种方法更适用于较小的数组或者数组内容已知的情况。

cpp 复制代码
#include <vector>
#include <iostream>

int main() {
    double mtx[16] = { /* 初始化你的数组 */ };

    // 使用列表初始化,适合较小数组
    std::vector<double> vec = {mtx[0], mtx[1], mtx[2], mtx[3], mtx[4], mtx[5], mtx[6], mtx[7],
                               mtx[8], mtx[9], mtx[10], mtx[11], mtx[12], mtx[13], mtx[14], mtx[15]};

    // 输出验证
    for (double val : vec) {
        std::cout << val << " ";
    }
    std::cout << std::endl;

    return 0;
}

注意:虽然方法三可以工作,但是如果数组较大或者内容复杂,使用前两种方法会更加简洁和高效。

方法四:使用 std::array 作为中间步骤(如果数组大小固定)

如果你的数组大小是固定的,可以考虑使用 std::array 作为中间步骤,然后再转换为 std::vector

cpp 复制代码
#include <vector>
#include <array>
#include <iostream>

int main() {
    std::array<double, 16> mtx = { /* 初始化你的数组 */ };

    // 转换为vector
    std::vector<double> vec(mtx.begin(), mtx.end());

    // 输出验证
    for (double val : vec) {
        std::cout << val << " ";
    }
    std::cout << std::endl;

    return 0;
}

根据你的需求和具体使用场景,可以选择以上适合的方法来完成数组的传递。


相关推荐
RuoZoe7 小时前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
blasit8 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
祈安_4 天前
C语言内存函数
c语言·后端
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端