【发布时间】:2021-04-01 16:37:17
【问题描述】:
我正在创建一个名为“matrix”的类,其类成员为std::vector<std::vector<T>>,在类构造函数中设置其大小的最佳优化方法是什么?我在m 行的构造函数中使用matrix_.resize(m),然后使用for 循环设置其行值(矩阵m x n)。我的问题是:
-
使用 .resize() 是一种好方法吗?听说效率不高,但我想不出别的了
-
例如,当我使用
std::vector<std::vector<T>> = matrix_;并且我使用matrix_.resize(m)时,matrix_现在将为“m”std::vector<T>对象提供“m”个空格,但是如果它,matrix_将如何管理内存不知道其对象的大小(std::vector<T>)?如果每个对象的大小(1000)或更大怎么办?
#include <iostream>
#include <vector>
// Matrix of shape m x n, 'm' lines and 'n' columns
template <typename T>
class matrix {
private:
typedef T value_type;
typedef std::vector<value_type> row;
std::vector<row> matrix_;
public:
// Default constructor, initializes a matrix of size 1x1, with element 0.
matrix() {
matrix_.resize(1);
row temp = {0};
matrix_[0] = temp;
};
matrix(size_t m, size_t n) {
matrix_.resize(m);
// Appends 'm' rows to the matrix_
for (size_t i = 0; i < m; i++) {
row temp(n); // Creates a row of 'n' columns
matrix_[i] = temp;
}
}
value_type& at (size_t m, size_t n) {
return matrix_[m][n];
}
};
int main() {
matrix<double> first(2, 2);
first.at(0, 0) = 3.3;
first.at(0, 1) = 5.2;
first.at(1, 0) = 8.9;
first.at(1, 1) = 1.4;
return 0;
}
【问题讨论】:
-
不要使用二维向量。使用大小为 N x M 的一维向量,然后使用数学将
m和n转换为单个索引,如下所示:stackoverflow.com/questions/2151084/… -
1.你不需要
resize,因为你可以在vector的构造函数中这样做,但它没有太大的危害。 -
2.只是作为一维
vector?我真的没有得到你的关心。 -
是的,顶层vector负责管理
m其他vector。那些m向量都完全能够处理它们自己的n标量元素。但无论如何你都应该使用一个平面 n*m 向量。 -
fwiw,
sizeof( std::vector<T>)是一个常数,无论向量包含多少元素。元素不存储在向量中,但它们是动态分配的
标签: c++ matrix data-structures c++14