- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在为我类的一个项目编写代码,它产生了非常不寻常的结果。行和列值以数百万的随机数结尾,它最终会抛出异常,我不明白为什么。
#include <iostream>
using namespace std;
class SparseRow {
protected:
int row;
int col;
int value;
public:
SparseRow();
SparseRow(int inRow, int inCol, int inVal);
SparseRow(const SparseRow& newRow);
SparseRow& operator=(const SparseRow& newRow);
~SparseRow();
void display();
int getRow();
int getCol();
int getValue();
void setRow(int inRow);
void setCol(int inCol);
void setValue(int inVal);
};
class SparseMatrix {
protected:
int noRows;
int noCols;
int commonValue;
int noSparseValues;
SparseRow *myMatrix;
void setNoSparseValues(int noSV);
public:
SparseMatrix();
SparseMatrix(int rows, int cols, int cv, int noSV);
SparseMatrix(const SparseMatrix& matrix);
SparseMatrix& operator=(const SparseMatrix& matrix);
~SparseMatrix();
void readMatrix();
SparseMatrix* transpose();
SparseMatrix* multiply(SparseMatrix& M);
SparseMatrix* add(SparseMatrix& M);
void display();
void displayMatrix();
int getNoRows();
int getNoCols();
int getCommonValue();
int getNoSparseValues();
int getValue(int row, int col);
void setValue(int row, int col, int val);
};
SparseRow::SparseRow() {
row = -1;
col = -1;
value = 0;
}
SparseRow::SparseRow(int inRow, int inCol, int inVal) {
row = inRow;
col = inCol;
value = inVal;
}
SparseRow::SparseRow(const SparseRow& newRow) {
row = newRow.row;
col = newRow.col;
value = newRow.value;
}
SparseRow& SparseRow::operator=(const SparseRow& newRow) {
if (this != &newRow) {
row = newRow.row;
col = newRow.col;
value = newRow.value;
}
return *this;
}
SparseRow::~SparseRow() {
cout << "Deleting SparseRow with values: " << endl;
display();
}
void SparseRow::display() {
cout << "Row: " << row << ", Column: " << col << ", Value: " << value << endl;
}
int SparseRow::getRow() {
return row;
}
int SparseRow::getCol() {
return col;
}
int SparseRow::getValue() {
return value;
}
void SparseRow::setRow(int inRow) {
row = inRow;
}
void SparseRow::setCol(int inCol) {
col = inCol;
}
void SparseRow::setValue(int inVal) {
value = inVal;
}
SparseMatrix::SparseMatrix() {
noRows = 0;
noCols = 0;
commonValue = 0;
noSparseValues = 0;
}
SparseMatrix::SparseMatrix(int rows, int cols, int cv, int noSV) {
noRows = rows;
noCols = cols;
commonValue = cv;
noSparseValues = noSV;
myMatrix = new SparseRow[rows * cols];
}
SparseMatrix::SparseMatrix(const SparseMatrix& matrix) {
noRows = matrix.noRows;
noCols = matrix.noCols;
commonValue = matrix.commonValue;
noSparseValues = matrix.noSparseValues;
myMatrix = matrix.myMatrix;
}
SparseMatrix& SparseMatrix::operator=(const SparseMatrix& matrix) {
if (this != &matrix) {
delete[] myMatrix;
noRows = matrix.noRows;
noCols = matrix.noCols;
commonValue = matrix.commonValue;
noSparseValues = matrix.noSparseValues;
myMatrix = matrix.myMatrix;
}
return *this;
}
SparseMatrix::~SparseMatrix() {
cout << "Deleting SparseMatrix with values: " << endl;
display();
delete[] myMatrix;
}
void SparseMatrix::readMatrix() {
int count = 0;
int val;
for (int i = 0; i < noRows; i++) {
for (int j = 0; j < noCols; j++) {
cin >> val;
if (val != commonValue) {
myMatrix[count].setRow(i);
myMatrix[count].setCol(j);
myMatrix[count].setValue(val);
// Why does C++ prevent me from calling a constructor on objects in an array? It doesn't make sense.
count++;
}
}
}
if (count != noSparseValues) {
cout << "ERROR: Incorrect number of sparse values! Changing to correct number." << endl;
noSparseValues = count;
}
}
SparseMatrix* SparseMatrix::transpose() {
SparseMatrix *newMatrix = new SparseMatrix(noCols, noRows, commonValue, noSparseValues);
for (int i = 0; i < noSparseValues; i++) {
newMatrix->setValue(myMatrix[i].getCol(), myMatrix[i].getRow(), myMatrix[i].getValue());
}
return newMatrix;
}
SparseMatrix* SparseMatrix::multiply(SparseMatrix& M) {
if (noCols != M.getNoRows()) {
cout << "ERROR: Matrices cannot be multiplied!" << endl;
return NULL;
}
SparseMatrix *newMatrix = new SparseMatrix(noRows, M.getNoCols(), commonValue, noRows * M.getNoCols());
// Why does C++ prevent me from creating an array to store this information? It doesn't make sense.
int SVCount = 0;
for (int i = 0; i < noRows; i++) {
for (int j = 0; j < M.getNoCols(); j++) {
int sum = 0;
for (int k = 0; k < noCols; k++) {
sum += getValue(i, k) * M.getValue(k, j);
}
if (sum != newMatrix->getCommonValue()) {
SVCount++;
}
newMatrix->setValue(i, j, sum);
}
}
newMatrix->setNoSparseValues(SVCount);
return newMatrix;
}
SparseMatrix* SparseMatrix::add(SparseMatrix& M) {
if (noRows != M.getNoRows() || noCols != M.getNoCols()) {
cout << "ERROR: Matrices cannot be added!" << endl;
return NULL;
}
SparseMatrix *newMatrix = new SparseMatrix(noRows, noCols, commonValue + M.getCommonValue(), noRows * noCols);
int SVCount = 0;
for (int i = 0; i < noRows; i++) {
for (int j = 0; j < noCols; j++) {
int sum = getValue(i, j) + M.getValue(i, j);
if (sum != newMatrix->getCommonValue()) {
SVCount++;
}
newMatrix->setValue(i, j, sum);
}
}
newMatrix->setNoSparseValues(SVCount);
return newMatrix;
}
void SparseMatrix::display() {
for (int i = 0; i < noSparseValues; i++) {
myMatrix[i].display();
}
}
void SparseMatrix::displayMatrix() {
for (int i = 0; i < noRows; i++) {
for (int j = 0; j < noCols; j++) {
cout << getValue(i, j) << " ";
}
cout << endl;
}
}
int SparseMatrix::getNoRows() {
return noRows;
}
int SparseMatrix::getNoCols() {
return noCols;
}
int SparseMatrix::getCommonValue() {
return commonValue;
}
int SparseMatrix::getNoSparseValues() {
return noSparseValues;
}
void SparseMatrix::setNoSparseValues(int noSV) {
noSparseValues = noSV;
}
int SparseMatrix::getValue(int row, int col) {
for (int i = 0; i < noSparseValues; i++) {
if (myMatrix[i].getRow() == row && myMatrix[i].getCol() == col) {
return myMatrix[i].getValue();
}
}
return commonValue;
}
void SparseMatrix::setValue(int row, int col, int val) {
bool replacingSparse = (getValue(row, col) != commonValue);
bool replacingWithSparse = (val != commonValue);
int index = -1;
if (replacingSparse) {
for (int i = 0; i < noSparseValues; i++) {
if (myMatrix[i].getRow() == row && myMatrix[i].getCol() == col) {
index = i;
break;
}
}
if (replacingWithSparse) {
myMatrix[index].setValue(val);
}
else {
for (int i = index; i < noSparseValues; i++) {
myMatrix[i] = myMatrix[i + 1];
}
noSparseValues--;
}
}
else {
if (replacingWithSparse) {
for (int i = 0; i < noSparseValues; i++) {
if (myMatrix[i].getRow() > row || (myMatrix[i].getRow() >= row && myMatrix[i].getCol() > col)) {
index = i;
break;
}
}
for (int i = noSparseValues; i > index; i--) {
myMatrix[i] = myMatrix[i - 1];
}
myMatrix[index].setRow(row);
myMatrix[index].setCol(col);
myMatrix[index].setValue(val);
noSparseValues++;
}
}
}
int main() {
int n, m, cv, noNSV;
SparseMatrix* temp;
cin >> n >> m >> cv >> noNSV;
SparseMatrix* firstOne = new SparseMatrix(n, m, cv, noNSV);
firstOne->readMatrix();
cin >> n >> m >> cv >> noNSV;
SparseMatrix* secondOne = new SparseMatrix(n, m, cv, noNSV);
secondOne->readMatrix();
cout << "First one in sparse matrix format" << endl;
firstOne->display();
cout << "First one in normal matrix format" << endl;
firstOne->displayMatrix();
cout << "Second one in sparse matrix format" << endl;
secondOne->display();
cout << "Second one in normal matrix format" << endl;
secondOne->displayMatrix();
cout << "After Transpose first one in normal format" << endl;
temp = firstOne->transpose();
temp->displayMatrix();
cout << "After Transpose second one in normal format" << endl;
temp = secondOne->transpose();
temp->displayMatrix();
cout << "Multiplication of matrices in sparse matrix form:" << endl;
temp = secondOne->multiply(*firstOne);
temp->display();
cout << "Addition of matrices in sparse matrix form:" << endl;
temp = secondOne->add(*firstOne);
temp->display();
}
输入:
3 3 0 3
2 2 2
0 0 0
0 0 0
3 3 0 3
2 2 2
0 0 0
0 0 0
预期输出:(格式不完全相同,但数字应该相同)
First one in sparse matrix format
0, 0, 2
0, 1, 2
0, 2, 2
First one in normal matrix format
2 2 2
0 0 0
0 0 0
Second one in sparse matrix format
0, 0, 2
0, 1, 2
0, 2, 2
Second one in normal matrix format
2 2 2
0 0 0
0 0 0
After Transpose first one
2 0 0
2 0 0
2 0 0
After Transpose second one
2 0 0
2 0 0
2 0 0
Multiplication of matrices in sparse matrix form:
0, 0, 4
0, 1, 4
0, 2, 4
Addition of matrices in sparse matrix form:
0, 0, 4
0, 1, 4
0, 2, 4
实际输出:
First one in sparse matrix format
Row: 0, Column: 0, Value: 2
Row: 0, Column: 1, Value: 2
Row: 0, Column: 2, Value: 2
First one in normal matrix format
2 2 2
0 0 0
0 0 0
Second one in sparse matrix format
Row: 0, Column: 0, Value: 2
Row: 0, Column: 1, Value: 2
Row: 0, Column: 2, Value: 2
Second one in normal matrix format
2 2 2
0 0 0
0 0 0
After Transpose first one in normal format
0 0 0
2 0 0
2 0 0
After Transpose second one in normal format
0 0 0
2 0 0
2 0 0
Multiplication of matrices in sparse matrix form:
Row: 0, Column: 1, Value: 4
Row: 0, Column: 2, Value: 4
Row: 369, Column: -33686019, Value: 9
Addition of matrices in sparse matrix form:
(Exceptions thrown here, line 222 in code)
抛出的异常:
Project1.exe has triggered a breakpoint.
Unhandled exception at 0x777E8499 (ntdll.dll) in Project1.exe: 0xC0000374: A heap has been corrupted (parameters: 0x77825890).
最佳答案
我只会解决已发布代码中的部分问题。
他们的明确使用总是容易出错,并且在标准的每个新版本中都越来越不鼓励使用。在 OP 的代码中,他们拥有管理内存资源的责任,但在 C++ 中,当对象超出范围时,他们不会自动调用对象的析构函数。这就是像 std::unique_ptr
这样的智能指针可以做到。
让我们看看 main
中发生了什么:
int n, m, cv, noNSV;
SparseMatrix* temp; // <- Declaration far from initialization
cin >> n >> m >> cv >> noNSV;
SparseMatrix* firstOne = new SparseMatrix(n, m, cv, noNSV);
// ^^^^^^^^^^^^^^^^ Why?
// ...
temp = firstOne->transpose(); // <- Here the pointer is initialized
// ...
temp = secondOne->transpose(); // <- Here the pointer is overwritten, but the allocated memory
// isn't released, it leaks.
// ...
temp = secondOne->multiply(*firstOne); // <- Again...
// ...
temp = secondOne->add(*firstOne); // <- ...and again
// ...
// No 'delete' calls at the end, so no destructor is called for the previously allocated objects
这里使用指针的唯一原因是 SparseMatrix::transpose()
旨在返回一个,但它可以轻松地重新运行 SparseMatrix
(返回值优化将避免不必要的拷贝)。
对于 new
的每次调用都应该对应一个 delete
并且由于像 transpose
这样的函数返回一个指向新分配的对象的指针, delete temp;
应该在覆盖 temp
之前调用,以确保调用正确的析构函数。
不过,在 C++ 中,我们应该利用 RAII (Resource Acquisition Is Initialization,也叫Scope-Bound Resource Management):
{ // <- Start of a scope
int n, m, cv, noNSV;
std::cin >> n >> m >> cv >> noNSV;
// Declare a variable using the constructor. Its lifetime begins here.
SparseMatrix firstOne(n, m, cv, noNSV);
// The same for 'secondOne'
// ...
// SparseSparse::transpose() here should return a SparseMatrix, not a pointer
SparseMatrix temp = firstOne.transpose();
// ...
// Here the matrix is reassigned (which can be cheap if move semantic is implemented)
temp = secondOne.transpose();
// ...
temp = secondOne.multiply(firstOne); // <- Again...
// ...
} // <- End of scope, all the destructors are called. No leaks.
这实际上与前一点有关,看看如何复制赋值运算符在发布的代码片段中实现:
SparseMatrix& SparseMatrix::operator=(const SparseMatrix& matrix) {
if (this != &matrix) { // <- debatable, see copy-and-swap idiom
delete[] myMatrix; // <- putted here makes this function not exception safe ^^
noRows = matrix.noRows;
noCols = matrix.noCols;
commonValue = matrix.commonValue;
noSparseValues = matrix.noSparseValues;
myMatrix = matrix.myMatrix; // <- The pointer is overwritten, but this is shallow copy
// what you need is a deep copy of the array
}
return *this;
}
此函数和其他特殊函数的正确实现将利用 copy-and-swap 惯用语,此处对其进行了巧妙的描述:
What is the copy-and-swap idiom?
此外,关于 OP 阅读功能中的评论:
for (int i = 0; i < noRows; i++) {
for (int j = 0; j < noCols; j++) {
cin >> val;
if (val != commonValue) {
myMatrix[count].setRow(i);
myMatrix[count].setCol(j);
myMatrix[count].setValue(val);
// Why does C++ prevent me from calling a constructor on objects in an array? It doesn't make sense.
count++;
}
}
}
提问者可以使用 new 的放置参数(放置新),那里:
for (int i = 0; i < noRows; i++) {
for (int j = 0; j < noCols; j++) {
cin >> val;
if (val != commonValue) {
new (myMatrix + count) SparseRow(i, j, val);
count++;
}
}
}
许多其他问题留给 OP 解决。
关于c++ - 是什么导致了我的代码中的堆损坏和无关值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54566751/
我想做的是让 JTextPane 在 JPanel 中占用尽可能多的空间。对于我使用的 UpdateInfoPanel: public class UpdateInfoPanel extends JP
我在 JPanel 中有一个 JTextArea,我想将其与 JScrollPane 一起使用。我正在使用 GridBagLayout。当我运行它时,框架似乎为 JScrollPane 腾出了空间,但
我想在 xcode 中实现以下功能。 我有一个 View Controller 。在这个 UIViewController 中,我有一个 UITabBar。它们下面是一个 UIView。将 UITab
有谁知道Firebird 2.5有没有类似于SQL中“STUFF”函数的功能? 我有一个包含父用户记录的表,另一个表包含与父相关的子用户记录。我希望能够提取用户拥有的“ROLES”的逗号分隔字符串,而
我想使用 JSON 作为 mirth channel 的输入和输出,例如详细信息保存在数据库中或创建 HL7 消息。 简而言之,输入为 JSON 解析它并输出为任何格式。 最佳答案 var objec
通常我会使用 R 并执行 merge.by,但这个文件似乎太大了,部门中的任何一台计算机都无法处理它! (任何从事遗传学工作的人的附加信息)本质上,插补似乎删除了 snp ID 的 rs 数字,我只剩
我有一个以前可能被问过的问题,但我很难找到正确的描述。我希望有人能帮助我。 在下面的代码中,我设置了varprice,我想添加javascript变量accu_id以通过rails在我的数据库中查找记
我有一个简单的 SVG 文件,在 Firefox 中可以正常查看 - 它的一些包装文本使用 foreignObject 包含一些 HTML - 文本包装在 div 中:
所以我正在为学校编写一个 Ruby 程序,如果某个值是 1 或 3,则将 bool 值更改为 true,如果是 0 或 2,则更改为 false。由于我有 Java 背景,所以我认为这段代码应该有效:
我做了什么: 我在这些账户之间创建了 VPC 对等连接 互联网网关也连接到每个 VPC 还配置了路由表(以允许来自双方的流量) 情况1: 当这两个 VPC 在同一个账户中时,我成功测试了从另一个 La
我有一个名为 contacts 的表: user_id contact_id 10294 10295 10294 10293 10293 10294 102
我正在使用 Magento 中的新模板。为避免重复代码,我想为每个产品预览使用相同的子模板。 特别是我做了这样一个展示: $products = Mage::getModel('catalog/pro
“for”是否总是检查协议(protocol)中定义的每个函数中第一个参数的类型? 编辑(改写): 当协议(protocol)方法只有一个参数时,根据该单个参数的类型(直接或任意)找到实现。当协议(p
我想从我的 PHP 代码中调用 JavaScript 函数。我通过使用以下方法实现了这一点: echo ' drawChart($id); '; 这工作正常,但我想从我的 PHP 代码中获取数据,我使
这个问题已经有答案了: Event binding on dynamically created elements? (23 个回答) 已关闭 5 年前。 我有一个动态表单,我想在其中附加一些其他 h
我正在尝试找到一种解决方案,以在 componentDidMount 中的映射项上使用 setState。 我正在使用 GraphQL连同 Gatsby返回许多 data 项目,但要求在特定的 pat
我在 ScrollView 中有一个 View 。只要用户按住该 View ,我想每 80 毫秒调用一次方法。这是我已经实现的: final Runnable vibrate = new Runnab
我用 jni 开发了一个 android 应用程序。我在 GetStringUTFChars 的 dvmDecodeIndirectRef 中得到了一个 dvmabort。我只中止了一次。 为什么会这
当我到达我的 Activity 时,我调用 FragmentPagerAdapter 来处理我的不同选项卡。在我的一个选项卡中,我想显示一个 RecyclerView,但他从未出现过,有了断点,我看到
当我按下 Activity 中的按钮时,会弹出一个 DialogFragment。在对话框 fragment 中,有一个看起来像普通 ListView 的 RecyclerView。 我想要的行为是当
我是一名优秀的程序员,十分优秀!