我有一个问题,但答案我没有找到。我写了一些组合学解算器和单独的主要保存结构,分成称为Matrix的类。我填写了回溯算法。当我创建一个指向Matrix的新指针实例并经常调用方法集并在类上取消设置时Matrix性能下降2倍。它比以前慢了2倍。但是,如果我创建嵌套类,性能将是正常的。但我不知道为什么?是否有任何解决方案如何没有嵌套类的单独类,但性能会好吗?感谢您的时间。我粘贴Matrix.h和Matrix.cpp。项目我在macOsx和linux上进行了测试,由g ++ 4.2.1和-O2声明编译
class Matrix {
private:
int rows;
int columns;
int filledCells = { 0 };
int * data = nullptr;
int * freeCellInColumn = nullptr;
public:
Matrix(int rows, int columns);
~Matrix();
void set(const int & column, const int & value);
void unset(const int & column);
int & get(const int & row, const int & column);
int & getFreeCellsInColumn(const int & column);
int getFilledCellsInColumn(const int & column);
int * getData();
const int & getFilledCells() const;
};
和定义是
#include <stdexcept>
#include "Matrix.h"
Matrix::Matrix(int rows, int columns) {
if (rows < 1 || columns < 1) {
std::runtime_error("Number of rows or columns at matrix is invalid.\n");
}
this->rows = rows;
this->columns = columns;
this->data = new int [rows * columns]();
this->freeCellInColumn = new int[columns]();
for (int i = 0; i < columns; i++) {
this->freeCellInColumn[i] = this->rows;
}
}
Matrix::~Matrix() {
delete [] this->data;
this->data = nullptr;
delete [] this->freeCellInColumn;
freeCellInColumn = nullptr;
}
void Matrix::set(const int & column, const int & value) {
this->data[(--this->freeCellInColumn[column]) * this->columns + column] = value;
++this->filledCells;
}
void Matrix::unset(const int & column) {
this->data[(this->freeCellInColumn[column]++) * this->columns + column] = 0;
--this->filledCells;
}
int * Matrix::getData() {
return this->data;
}
int & Matrix::get(const int & row, const int & column) {
return this->data[row * this->columns + column];
}
const int & Matrix::getFilledCells() const {
return this->filledCells;
}
int & Matrix::getFreeCellsInColumn(const int & column) {
return this->freeCellInColumn[column];
}
int Matrix::getFilledCellsInColumn(const int & column) {
return this->rows - this->freeCellInColumn[column];
}
我粘贴嵌套类的部分,我在Labeling类中的嵌套类的意思是在类标签中声明类Matrix, method int * getData()我只使用一次打印结果。
class Labelling {
private:
class Matrix {
private:
int rows;
int columns;
int filledCells = { 0 };
int * data = nullptr;
int * freeCellInColumn = nullptr;
public:
Matrix(int rows, int columns);
~Matrix();
void set(const int & column, const int & value);
void unset(const int & column);
int & get(const int & row, const int & column);
int & getFreeCellsInColumn(const int & column);
int getFilledCellsInColumn(const int & column);
int * getData();
const int & getFilledCells() const;
};
TextPrinter * printer;
NSumProblemSolver * solver;
Matrix * solution;
...};