【问题标题】:Resize dynamic string array [closed]调整动态字符串数组的大小[关闭]
【发布时间】:2018-03-31 20:58:17
【问题描述】:

如何在不使用 malloc/free 等 C 方法的情况下在 C++ 中调整动态多维数组 std::string** 的大小?

【问题讨论】:

  • 你为什么开始使用std::string**?为什么不使用std::vector<std::vector<std::string>>>
  • 你能用newdelete吗?
  • 每当您想到“动态数组”时,下一个想法应该始终std::vector
  • @PaulMcKenzie 我认为这可能是 OP 正在寻找的。他似乎来自C世界,可能他并没有意识到这种可能性。
  • @Kyu96 -- 我认为 std::vector 在内存上比数组更重。 -- 所有 vector 所做的就是将你想要做的事情包装在一个班级。最大的区别在于矢量是标准的、有据可查的、有效的,而且在速度方面,可能比您自己设计的更有效。

标签: c++ arrays string dynamic


【解决方案1】:

在 C++ 中不可能重新分配数组/矩阵。因此,如果您想调整数组大小,您需要使用 C 函数 reallocnew[] + copy + delete[] 的组合。

但最好的选择是使用 C++ 标准库 (std::vector),因为它允许您插入/删除/更新而无需考虑内存重新分配。

示例(C++ 11):

#include <string>
#include <vector>

int main(){
    // *using* is like a alias: when the compiler finds the type "stringVec" 
    // it will replace by "std::vector<std::string>"
    using stringVec = std::vector<std::string>;

    std::vector<stringVec> matrix;
    matrix.push_back({"1", "2", "3"}); // inserts a row
}

【讨论】:

  • 我建议可能解释(或删除)using 指令,因为 OP 显然不熟悉 C++。除此之外,很好的答案!
猜你喜欢
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多