将值从文件添加到双指针
add value from file to double pointer
my .h 文件
#ifndef ADJACENCYMATRIX_H_
#define ADJACENCYMATRIX_H_
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
class AdjacencyMatrix{
private:
int vertexCount;
int vertexFirst;
int edgeCount;
int **wage;
int **matrix;
public:
AdjacencyMatrix();
virtual ~AdjacencyMatrix();
bool createFromFile(string path);
void viewMatrix();
};
#endif /* ADJACENCYMATRIX_H_ */
我读取了表单文件,我想将其写入初始化的矩阵,但它不起作用。你可以帮我吗?
#include "AdjacencyMatrix.h"
AdjacencyMatrix::AdjacencyMatrix() {
this->vertexCount=0;
this->vertexFirst=-1;
this->edgeCount=0;
}
AdjacencyMatrix::~AdjacencyMatrix() { }
bool AdjacencyMatrix::createFromFile(string path) {
fstream file;
file.open(path.c_str(), fstream::in);
if (file.good())
{
int vertexF,vertexE,wag;
cout << "file opened" << endl;
file >> this->edgeCount;
file >> this->vertexCount;
file >> this->vertexFirst;
matrix = new int *[edgeCount];
wage = new int *[edgeCount];
for (int i = 0; i < vertexCount; i++)
{
matrix[i]=new int[edgeCount];
wage[i]=new int[edgeCount];
}
//fill matrix by zeros
for (int i = 0; i < vertexCount; i++)
{
for(int j=0; j<edgeCount;j++)
{
matrix[i][j]=0;
wage[i][j]=0;
}
}
// fill matrix by 1
for(int i=0; i<edgeCount; i++)
{
file >> vertexF >> vertexE >> wag;
cout << " w " << wag;
matrix[vertexF][vertexE] = 1;
}
file.close();
return true;
}
cout << "File does not opened" << endl;
return false;
}
void AdjacencyMatrix::viewMatrix(){
cout << " Adjacency Matrix ";
for(int i=0; i<vertexCount; i++)
{
for(int j=0; i<edgeCount;i++) {
cout << this->matrix[i][j] << " ";
}
cout<< endl;
}
}
并且这部分不起作用(我的意思是,什么都没有显示,showMatrix() 不起作用)。我想从文件中获取值,然后将其编写为matrix[x][y] = 1
因为我想创建一个图形路径。
for(int i=0; i<edgeCount; i++)
{
file >> vertexF >> vertexE >> wag; // cout work in this line
matrix[vertexF][vertexE] = 1; // does not work
}
矩阵的大小是错误的:
matrix = new int *[edgeCount]; // wrong size
wage = new int *[edgeCount]; // wrong size
for (int i = 0; i < vertexCount; i++)
{
matrix[i]=new int[edgeCount];
wage[i]=new int[edgeCount];
}
定义矩阵时,应改用vertexCount
,如下所示:
matrix = new int *[vertexCount];
wage = new int *[vertexCount];
这可能会导致分段错误或奇怪的行为。
此外,当您读取用户提供的数据时,您应该验证它们:
file >> vertexF >> vertexE >> wag;
matrix[vertexF][vertexE] = 1;
你确定vertexF
和vertexE
不比vertexCount - 1
和edgeCount - 1
大吗?
相关文章:
- 是否允许向空指针添加零?
- 将指向结构数组的指针添加到 std::map
- 将 char* 推送到矢量时出现问题,但在每次迭代后,它会将指向相同值缓冲区的指针添加到矢量中
- 将对象指针添加到向量后的值更改
- 将指针添加到成员对象中的指针动态阵列
- 需要一些关于使用指针添加C++数组的建议
- 如何将函数指针添加到现有va_list
- 为什么对象属性的值在 c++ 中将其指针添加到映射后返回零
- 将对象指针添加到位于类内部的指向对象的指针向量
- 无法将对象上的指针添加到集合
- 将指针添加到不同命名空间中的类时出错
- 向无符号字符指针添加短int
- Delphi中的类型转换指针添加
- 如何将节点指针添加到矢量指针
- 我可以向数组指针添加元素吗
- 向指针添加"const"可以帮助优化吗?
- 向函数指针添加constness时会发生什么
- 向指针添加偏移量
- 为什么使用std::next而不是向指针添加整数
- 无法将指针添加到类指针向量数组