c++作用域问题:创建一个矩阵类而不浪费空间
C++ Scope issue: Creating a matrix class without wasting space
有一个小类让我很困扰:
class matrix{
string name;
int rowSize, columnSize;
// I could declare double m[100][100]; here but that would be ugly
public:
void createMat(){
cout << "Enter Matrix Name:";
cin >> name;
cout << "Enter number of rows: ";
cin >> rowSize;
cout << "Enter no. of columns: ";
cin >> columnSize;
double m[rowSize][columnSize]; //needs to be available to readMat()
cout << "Enter matrix (row wise):n";
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < columnSize; j++){cin >> m[i][j];}
cout<<'n';
}
}
void readMat(){
cout << "Matrix " << name << " :n";
for(int i = 0 ; i < rowSize; i++){
for(int j = 0; j < columnSize; j++){ cout << m[i][j] << ' ';}
cout<<'n';
}
}
};
如何以最优的方式使m
对createMat()
和readMat()
都可用?
尝试允许用户输入矩阵的维度是不必要的吗?
从我的角度来看,我觉得定义矩阵的最大大小在需要更多元素的情况下会过于限制,或者如果不需要那么多元素的话会太多。
您应该使用动态大小的内存块,并在运行时根据用户输入分配它。这里,我使用std::vector
:
class matrix{
std::string name;
int rowSize, columnSize;
std::vector<double> m;
public:
void createMat(){
std::cout << "Enter Matrix Name:";
std::cin >> name;
std::cout << "Enter number of rows: ";
std::cin >> rowSize;
std::cout << "Enter no. of columns: ";
std::cin >> columnSize;
m.resize(rowSize*columnSize);
std::cout << "Enter matrix (row wise):n";
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < columnSize; j++){
std::cin >> m[i*columnSize+j];
}
std::cout<<'n';
}
}
void readMat() {
std::cout << "Matrix " << name << " :n";
for(int i = 0 ; i < rowSize; i++){
for(int j = 0; j < columnSize; j++) {
std::cout << m[i*columnSize+j] << ' ';
}
std::cout<<'n';
}
}
};
我对你的问题的回答是:
- 使其成为类成员(听起来很明显,但你期望什么样的答案?)
- 很可能允许用户设置矩阵大小是有意义的…但这真的取决于你需要什么。
我会做一些不同的事情,特别是:
-
代替
createMat()
,我将使用类构造函数来执行初始化杂务(构造函数的存在正是因为这个原因)。 -
然后我将元素存储在
private
1D数组element[rowSize*columnSize]
中(在构造函数中动态分配)。 -
然后创建
void setElement(i,j)
和double getElement(i,j)
方法
(考虑查看EIGEN库,这是一个非常光滑且易于使用的线性代数库,带有一些类似matlab的味道)
您需要将m
定义为类成员并进行动态内存分配。
class matrix{
string name;
int rowSize, columnSize;
double **m;
void createMat(){
m = new double*[rowSize];
for(int i = 0; i < rowSize; ++i)
m[i] = new double[columnSize];
}
}
这里有详细的教程:http://www.cs.umb.edu/~mweiss/cs410_f04/ppts/cs410-7.pdf
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- '使用命名空间{嵌套在另一个命名空间中的某个命名空间}"
- 使用另一个命名空间中的函数C++
- 使用命名空间在另一个".cpp"文件中定义
- 是否可以在专用内存空间中分配一个为提升管理共享内存而创建的对象
- C++中是否有一个函数可以为您获取指向该节点的所有指针的地址空间
- C ++使用getline,输出在开头带有一个额外的空间
- 如何使用另一个项目命名空间?
- 使用匿名命名空间中的函数或另一个文件中的静态函数不应该出错吗?
- 在模板参数的函数中使用一个命名空间或另一个命名空间
- 由另一个对象重用对象的空间
- 是否有一个很好的方法可以在C 11中打印出像JSON一样的Trie结构(仅迭代解决方案)的扁平命名空间
- 在同一C 源文件中使用多个名称空间是一个好习惯吗?
- C++另一个命名空间中函数的 ADL
- 如何在另一个名称空间内从另一个命名空间内明确专业化功能模板
- 我可以在标头中将一个命名空间"import"到另一个命名空间中吗?
- ptrA = ptrB 是否等同于 ptrA = &*ptrB?,空值是否共享一个地址空间?
- 我可以定义一个(键入的)常数,该常数确定不占据可执行文件中的空间
- 在C 的COUT系列中创建一个空间
- 为什么主可执行文件和 dlopen 加载的共享库共享命名空间静态变量的一个副本?