我有一个二维数组,其中列的大小长度不一样。那么如何动态循环该二维数组中的所有元素呢?
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/