c++ - 如何在C++中循环遍历具有不同长度的动态2D数组

标签 c++ pointers

我有一个二维数组,其中列的大小长度不一样。那么如何动态循环该二维数组中的所有元素呢?

string** arr = new string*[4];
    arr[0] = new string[5];
    arr[1] = new string[3];
    arr[2] = new string[4];
    arr[3] = new string[2];

最佳答案

使用这样的动态数组将变得更加难以维护,并且与使用std::vector相比并没有真正给您带来任何好处。您将需要分别存储每个数组的大小。
例:

#include <iterator>
#include <memory>
#include <utility>

template<typename T>
struct myarr {
    myarr() = default;
    myarr(size_t size) : arr(std::make_unique<T[]>(size)), m_size(size) {}

    T& operator[](size_t idx) { return arr[idx]; }
    const T& operator[](size_t idx) const { return arr[idx]; }

    auto cbegin() const { return &arr[0]; }
    auto cend() const { return std::next(cbegin(), m_size); }
    auto begin() const { return cbegin(); }
    auto end() const { return cend(); }
    auto begin() { return &arr[0]; }
    auto end() { return std::next(begin(), m_size); }

private:
    std::unique_ptr<T[]> arr;
    size_t m_size;
};

int main() {
    myarr<myarr<std::string>> arr(4);
    arr[0] = myarr<std::string>(5);
    arr[1] = myarr<std::string>(3);
    arr[2] = myarr<std::string>(4);
    arr[3] = myarr<std::string>(2);

    for(auto& inner : arr) {
        for(const std::string& str : inner) {
            // do stuff
        }
    }
}
基于std::vector的代码仅需要以下内容,并提供了更大的灵活性:
例:
std::vector<std::vector<std::string>> arr(4);
arr[0].resize(5);
arr[1].resize(3);
arr[2].resize(4);
arr[3].resize(2);

关于c++ - 如何在C++中循环遍历具有不同长度的动态2D数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63765095/

相关文章:

c++ - 整数提升、有符号/无符号和 printf

c - 从 int 函数返回 char * 而不使用指针?

c++ - 数组结束时指针不应该指向 nullptr 吗?

c++ - 如何将数据写入进程/内存?

c++ - 错误 : could not convert 'p1' from 'Person (*)()' to 'Person'

c++ - 是否有必要在构造函数中初始化一个私有(private)列表类成员?

c++ - 如何验证是否选中了多个复选框

将指针转换为二维数组

c - 全局变量声明如何解决C中的栈溢出问题?

c++ - 有没有办法创建由 `std::function<>` 包装的函数的哈希值?