Hi All
I searched the web for this question and tried lots of ways but none of them have worked so far. here is my problem:
I have a txt file including three columns of numbers or triples separated by space. The first two numbers are row and column index and the third one is the entry. There is also a single number at the first line for the size of matrix. So
it could be like this:
5
0 1 2
0 3 6
1 0 2
2 1 3
2 4 7
3 0 6
3 1 8
4 3 9
meaning that matrix is 5x5 and for example the [0][1] entry is 2 and so on.
I tried lots of methods however none of them were correct. I appreciate your help.
well yeah not listed entries could be zero. This is an unsuccessful try(of course it is part of a bigger code)
1 2 3 4 5 6 7 8 9 10 11
double** amat;
ifstream adj_mat("adjgraph2.txt");
int u, v, w;
string line;
// int num = getline(adj_mat, line);
getline(adj_mat, line);
//int vertexCount = stoi(num);
int vertexCount = 5;
while (adj_mat >> u >> v >> w) {
amat[u][v] = w;
}
the comment out line was a try to make the string into int which did not work. So I entered the vertexCount manually. However this does not work too.
The main problem with your attempt is that you never allocate any memory for what presumably looks like a double-pointer to a 2D array (amat). As it currently stands, amat is just a junk pointer.
I would say use an std::vector<int>... but I am going to assume, like most assignments I see on this website, that you probably aren't allowed to use them for some reason.
Regardless, I'll show you both methods to allocating data for 2D array.
Here's how you allocate a 2D array with std::vector. This is the preferred way.
// Example program
#include <iostream>
#include <vector>
int main()
{
int mat_size = 5; // get size
//
// Allocation:
//
std::vector<std::vector<int>> amat(mat_size); // allocate the outer array
for (int i = 0; i < mat_size; i++)
{
amat[i] = std::vector<int>(mat_size, 0); // allocate each inner array
}
//
// Processing with the Matrix:
//
amat[0][1] = 2;
amat[4][3] = 9;
// ...
std::cout << amat[0][1] << std::endl;
std::cout << amat[4][3] << std::endl;
//
// No need to clean up resources -- this is done by the std::vector object itself
//
}
Here's how to allocate a 2D array using raw arrays that are new'd and delete'd. Only use this way if you have to.
// Example program
#include <iostream>
int main()
{
int mat_size = 5; // get size
//
// Allocation:
//
double** amat = newdouble*[mat_size]; // allocate the outer array
for (int i = 0; i < mat_size; i++)
{
amat[i] = newdouble[mat_size](); // allocate each inner array
}
//
// Processing with the Matrix:
//
amat[0][1] = 2;
amat[4][3] = 9;
// ...
std::cout << amat[0][1] << std::endl;
std::cout << amat[4][3] << std::endl;
//
// Deallocation (Clean-up):
//
for (int i = 0; i < mat_size; i++)
{
delete[] amat[i];
}
delete[] amat;
}
Now try to apply this code to what you have, and see what you can get out of it.
Remember to use print statements to see if you're getting a valid result.