【问题标题】:c++ dynamecly fill 2d vector when there is unknown rows or columns当存在未知的行或列时,c ++动态填充二维向量
【发布时间】:2023-01-23 16:03:58
【问题描述】:

我试图了解如何动态保存二维向量数组(或者它可以是 C++ 中的其他容器) 当我不知道每个原始文件中的行号和列号时,我可以填写 dynameclly 我现在拥有的是这样的东西,但正如您所看到的,我必须提前定义原始数据和列的数量

 std::vector<std::vector<BaseColumn*>> csv(1, std::vector<BaseColumn*> (1));
    std::string test = "d";
    Column<std::string>* tmpString = new Column<std::string>(Types::string,test);
    csv[0].push_back(tmpString);   
    csv[0].push_back(tmpString);
    csv[0].push_back(tmpString);
    csv[1].push_back(tmpString); //<--- Here im getting Segmentation fault
    csv[1].push_back(tmpString); 
    csv[1].push_back(tmpString); 
    csv[1].push_back(tmpString); 


Thread 1 received signal SIGSEGV, Segmentation fault.
0x00007ff655703f1a in std::__new_allocator<BaseColumn*>::construct<BaseColumn*, BaseColumn*> (this=0x1af24052af8, __p=0xabababababababab) at C:/msys64/mingw64/include/c++/12.1.0/bits/new_allocator.h:175
175     { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

我的问题很简单如何构建二维动态容器......

【问题讨论】:

    标签: c++ c++11 multidimensional-array stdvector


    【解决方案1】:
    std::vector<...> csv(1, ...);
    

    在这里你说向量只有一元素。这意味着任何不等于 0 的索引都将越界。

    你可能想要

    std::vector<...> csv(2);  // Let the nested vectors be default-initialized and *empty*
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-07
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      相关资源
      最近更新 更多