如何解决如何在 C++ 中创建一个 2D 列表而不是通过数组或向量?
我想创建一个二维列表(n * c)(不是数组/向量),我的代码如下:
int n = 3;
int c = 2;
list<list<int>> S;
list<int> row;
for (int j = 0; j < c; j++)
{
row.push_back({});
}
for (int i = 0; i < n; i++)
{
S.push_back(row);
}
我不知道代码格式是否正确?
例如,当我使用 2D 列表时,我该怎么说 S[k][r] = S[k-1][r]?
解决方法
您不能使用 list
做到这一点,因为它没有重载随机访问运算符。以下是使用向量的方法:
#include <vector>
template <class T>
struct Matrix final {
private:
[[no_unique_address]] std::vector<T> data_;
[[no_unique_address]] int width_;
[[no_unique_address]] int height_;
[[nodiscard]] int index(int const row,int const col) const noexcept {
return width_ * row + col;
}
public:
Matrix(int const width,int const height)
: data_(width * height),width_(width),height_(height) {}
[[nodiscard]] auto width() const noexcept { return width_; }
[[nodiscard]] auto height() const noexcept { return height_; }
[[nodiscard]] auto& get(int const row,int const col) noexcept {
return data_[index(row,col)];
}
[[nodiscard]] auto& get(int const row,int const col) const noexcept {
return data_[index(row,col)];
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。