You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优雅地为嵌套vector中的每个子vector预留指定内存?

更优雅的嵌套vector内存预留实现方式

首先得提一下你原代码里的两个小问题,避免后续踩坑:

  1. 用C风格数组std::vector<...> pointcloud_vector[number_of_pointcloud]存储vector,当number_of_pointcloud是运行时变量时,这属于编译器扩展特性,并不符合C++标准,移植性会有问题。
  2. 循环条件pointcloud_vector->size()是错误的——数组名退化为指针后,->size()取的是第一个vector的大小,而不是数组的元素个数,应该用number_of_pointcloud。

接下来给你几种更优雅、更符合现代C++风格的实现方式:

方案一:范围for循环 + vector of vector

这是最直观易懂的方式,用标准的std::vector替代C风格数组,配合范围for循环简化代码:

int number_of_pointcloud = 666;
// 直接初始化外层vector,包含number_of_pointcloud个空的子vector
std::vector<std::vector<pcl::PointCloud<PointXYZIR>>> pointcloud_vector(number_of_pointcloud);
int size_small_pointcloud = cloud_in.size() / number_of_pointcloud;

// 遍历每个子vector,为其预留指定大小的内存
for (auto& sub_vec : pointcloud_vector) {
    sub_vec.reserve(size_small_pointcloud);
}

方案二:STL算法 + Lambda表达式

如果偏好函数式编程风格,可以用std::for_each配合lambda来实现,代码更紧凑:

#include <algorithm> // 需要包含algorithm头文件

int number_of_pointcloud = 666;
std::vector<std::vector<pcl::PointCloud<PointXYZIR>>> pointcloud_vector(number_of_pointcloud);
int size_small_pointcloud = cloud_in.size() / number_of_pointcloud;

// 用for_each遍历外层vector的所有元素,执行预留操作
std::for_each(pointcloud_vector.begin(), pointcloud_vector.end(),
    [size_small_pointcloud](auto& sub_vec) {
        sub_vec.reserve(size_small_pointcloud);
    });

方案三:初始化时直接完成预留

如果想在构造外层vector的同时就完成子vector的内存预留,可以用std::generate_n来实现,一步到位:

#include <algorithm>
#include <iterator> // 需要包含iterator头文件

int number_of_pointcloud = 666;
int size_small_pointcloud = cloud_in.size() / number_of_pointcloud;

std::vector<std::vector<pcl::PointCloud<PointXYZIR>>> pointcloud_vector;
// 先给外层vector预留空间,避免多次扩容
pointcloud_vector.reserve(number_of_pointcloud);

// 生成number_of_pointcloud个已预留内存的子vector
std::generate_n(std::back_inserter(pointcloud_vector), number_of_pointcloud,
    [size_small_pointcloud]() {
        std::vector<pcl::PointCloud<PointXYZIR>> sub_vec;
        sub_vec.reserve(size_small_pointcloud);
        return sub_vec;
    });

这些方案的优势在于:

  • 用std::vector替代C风格数组,自动管理内存,兼容性和安全性更好;
  • 避免手动维护循环索引,减少出错概率;
  • 代码意图更清晰,可读性更强,符合现代C++的编程习惯。

内容的提问来源于stack exchange,提问作者tony497

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:23:30