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

嵌套vector无法使用at函数?C++嵌套向量定义问题排查与修复

错误原因与修复方案

核心错误点

  1. 类型不匹配
    你定义的nest<int>等价于std::vector<int>,是一维容器,但你试图初始化的是二维结构。后续调用arr.at(0).at(0)时,arr.at(0)返回的是int类型,而int没有at()成员函数,这是编译报错的直接原因。

  2. 初始化语法错误
    代码里的(1, 2, 3)是C++的逗号表达式,它会依次计算每个子表达式,最终返回最后一个值(比如(1,2,3)的结果是3)。这导致你的一维vector被错误初始化为{3, 6, 9},完全偏离了二维数组的预期。

修复步骤与代码

  1. 修正容器类型
    要实现二维嵌套vector,需要将类型声明为nest<nest<int>>(对应std::vector<std::vector<int>>);如果是三维嵌套,就是nest<nest<nest<int>>>,以此类推。

  2. 修正初始化语法
    使用双层大括号包裹每一行的元素,替代原来的小括号,这样才能正确初始化每个子vector。

修正后的完整代码:

#include <iostream>
#include <vector>

template <typename T>
using nest = std::vector<T>;

int main()
{
  nest<nest<int>> arr = {{1, 2, 3},
                         {4, 5, 6},
                         {7, 8, 9}};
  std::cout << arr.at(0).at(0) << std::endl; // 输出1,正常运行
  return 0;
}

多层嵌套扩展示例

如果需要三维嵌套vector,可以这样写:

nest<nest<nest<int>>> three_d_arr = {
    {{1, 2}, {3, 4}},
    {{5, 6}, {7, 8}}
};
// 访问元素:three_d_arr.at(0).at(1).at(0) 返回3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:43:26