调整动态字符串数组的大小

Kyu*_*u96 -4 c++ arrays string dynamic

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

luc*_*exe 5

在C++中不可能重新分配数组/矩阵.因此,如果要调整数组大小,则需要使用C函数realloc或其组合new[] + 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
}
Run Code Online (Sandbox Code Playgroud)