传递具有可变大小的2D数组

Eri*_*ric 4 c++ arrays

我正在尝试将2D数组从函数传递到另一个函数.但是,数组的大小不是恒定的.大小由用户决定.

我试图研究这个,但没有太多运气.大多数代码和解释都是针对数组的恒定大小.

在我的函数中,A我声明了变量然后我稍微操作它,然后它必须传递给Function B.

void A()
{
      int n;
      cout << "What is the size?: ";
      cin >> n;

      int Arr[n-1][n];

      //Arr gets manipulated here

      B(n, Arr);
}

void B(int n, int Arr[][])
{
    //printing out Arr and other things

}
Run Code Online (Sandbox Code Playgroud)

rig*_*old 11

使用std::vector,如果你想动态调整大小的数组:

std::vector<std::vector<int>> Arr(n, std::vector<int>(n - 1));
B(Arr);

void B(std::vector<std::vector<int>> const& Arr) { … }
Run Code Online (Sandbox Code Playgroud)

  • `std :: vector`是基础知识.`new []`是C++的高级功能,仅在实现低级数据结构时使用. (13认同)
  • @MarounMaroun Bjarne Stroustrup(C++的创建者)有新手的书:["编程 - 使用C++的原理和实践"](http://www.stroustrup.com/Programming/).你知道吗?`vector`在页面~100,而`new`只在书的中间 - 页面~500. (6认同)
  • @MarounMaroun,不,它让你成为一个顽固的家伙,他认为每个程序员都需要在理智和现代*技术之前学习手动内存管理.呃. (5认同)
  • OP询问如何创建具有动态大小的数组,并告诉他如何执行此操作.`std :: vector`是一个实现_dynamic array_概念的抽象,你应该在需要_dynamic array_时使用它. (3认同)
  • Stroustrup:"到目前为止,C++具有允许程序员避免使用最麻烦的C功能的功能.例如,可以使用标准库容器(如vector,list,map和string)来避免最棘手的低级指针操纵".http://www.stroustrup.com/bs_faq.html (3认同)
  • 并且**"从根本上说,如果你理解向量,你就能理解C++"**([_Bjarne Stroustrup - C++的本质:C++ 84,C++ 98,C++ 11和C++中的例子14_ ](http://channel9.msdn.com/Events/GoingNative/2013/Opening-Keynote-Bjarne-Stroustrup)) (3认同)
  • 请让我们坚持技术要点,如果你想讨论切线使用[聊天](http://chat.stackoverflow.com/rooms/10/loungec)而不是评论. (3认同)
  • @MarounMaroun,确实如此.地狱,它走得更远,并将在以后为OP节省一些真正的严重问题. (2认同)