get value from another class c++ - c++

Hello I have a getter in adjacencyMatrix class
int AdjacencyMatrix::getVertexFirst() const { return vertexFirst; }
and constructor
AdjacencyMatrix::AdjacencyMatrix() {
this->vertexCount=0;
this->vertexFirst=0;
this->edgeCount=0;
this->matrix=0;
this->wage=0;
}
bool AdjacencyMatrix::createFromFile(string path) {
fstream file;
file.open(path.c_str(), fstream::in);
if (file.good())
{
int vertexF,vertexE,wag;
file >> this->edgeCount;
file >> this->vertexCount;
file >> this->vertexFirst;
matrix = new int *[vertexCount];
wage = new int *[vertexCount];
for (int i = 0; i < vertexCount; i++)
{
matrix[i]=new int[vertexCount];
wage[i]=new int[vertexCount];
}
//fill matrix by zeros
for (int i = 0; i < vertexCount; i++)
{
for(int j=0; j<vertexCount;j++)
{
matrix[i][j]=0;
wage[i][j]=0;
}
}
// fill matrix by 1
for(int i=0; i<edgeCount; i++)
{
file >> vertexF >> vertexE >> wag;
this->matrix[vertexF][vertexE]=1;
this->wage[vertexF][vertexE]=wag;
}
file.close();
return true;
}
return false;
}
of course print works in Adjacency class
And now I want to have this value in Dijkstra class
//Dijkstra.cpp
#include "Dijkstra.h"
AdjacencyMatrix am;
bool Dijkstra::makeDijkstraAlgo() {
int vertexCount=am.getVertexCount();
int vertexFirst=am.getVertexFirst();
int **wage=am.getWage();
cout << vertexCount;
cout << vertexFirst;
.......... }
this is my main class
#include <iostream>
#include "Dijkstra.h"
#include "Screen.h"
using namespace std;
int main() {
AdjacencyMatrix am;
Dijkstra dijkstra;
am.createFromFile("matrix.txt");
dijkstra.makeDijkstraAlgo();
dijkstra.viewDijkstra();
return 0;
}
and this cout show only 0, but in AdjacencyMatrix show normal value. Can you help me ?
UPDATE
I notice that always will be 0 because I initialized value in constructor....
So How to make something like this
I create a matrix from file and add value to vertexCount etc.
am.createFromFile("matrix.txt");
now I want to get this value(vertexCount etc.) from adjacency matrix class to Dijkstry class and make
dijkstra.makeDijkstraAlgo();
dijkstra.viewDijkstra();
How can I solve it ?

You're creating one matrix but using another.
makeDijkstraAlgo uses the global matrix called ”am”, but main has its own matrix by the same name.
Get rid of the global and pass main's matrix to the function
bool Dijkstra::makeDijkstraAlgo(const AdjacencyMatrix& am) {
int vertexCount=am.getVertexCount();
int vertexFirst=am.getVertexFirst();
int **wage=am.getWage();
cout << vertexCount;
cout << vertexFirst;
// ...
}
int main() {
AdjacencyMatrix am;
Dijkstra dijkstra;
am.createFromFile("matrix.txt");
dijkstra.makeDijkstraAlgo(am);
dijkstra.viewDijkstra();
return 0;
}

Related

Unable to pass a function pointer to a member function of the class as an argument to another member function of the same class

I need help... appropriate questions have been asked in the comments. The programs has zero compiler errors and warnings!! I have concerns with calling a member function from another member function using function pointers. (To be precise, setMatrixto() is trying to call setElement() function using function pointer)
Plus somehow the "hello there" is not being printed to the console. I was expecting it to show up as output.Maybe the setMatrixto() is not getting called at all!!
Header File definition
#ifndef MATRIXOPERATIONS_H
#define MATRIXOPERATIONS_H
class MatrixOperations;
typedef int (MatrixOperations::*INTFUNC)(int,int);
typedef void (MatrixOperations::*VOIDFUNC)(int,int,int);
class MatrixOperations
{
public:
MatrixOperations();
MatrixOperations(int size);
~MatrixOperations();
//diagonal matrix funtions
void displayMatrixOf(INTFUNC f);
void setMatrixTo(VOIDFUNC f);
int getElement(INTFUNC from, int i, int j);
void setElement(VOIDFUNC to,int i ,int j, int value);
int fromDiagonalArray(int i, int j);
void toDiagonalArray(int i, int j, int value);
protected:
private:
int size;
int* a;
};
#endif // MATRIXOPERATIONS_H
CPP Implementation File
#include "MatrixOperations.h"
#include <iostream>
using namespace std;
MatrixOperations::MatrixOperations()
{
//ctor
size = 3;
a = new int[size];
}
MatrixOperations::MatrixOperations(int size)
{
//ctor
this->size = size;
a = new int[size];
}
MatrixOperations::~MatrixOperations()
{
//dtor
delete[] a;
}
///////////////////FUCNTION POINTER SECTION///////////////////////////////////
int MatrixOperations::getElement(INTFUNC from, int i, int j)
{
return (this->*from)(i,j);
}
void MatrixOperations::setElement(VOIDFUNC to,int i ,int j, int value)
{
(this->*to)(i,j,value);
}
/////////////////////////////////DIAGONAL ARRAY OPERATIONS/////////////////////////////////////////////////
int MatrixOperations::fromDiagonalArray(int i, int j)
{
if(i==j)
{
return a[i];
}
else
{
return 0;
}
}
void MatrixOperations::toDiagonalArray(int i, int j, int value)
{
a[i] = value;
}
///////////////////////////////////////////////////////////////////
void MatrixOperations::displayMatrixOf(INTFUNC f)
{
for(int i{0}; i < size; i++)
{
for(int j{0}; j < size; j++)
{
cout << getElement(f,i,j) << "\t"; //is this the correct way to send the function pointer?
}
cout << endl;
}
}
void MatrixOperations::setMatrixTo(VOIDFUNC f)
{
cout << "Hello there!!"; //not getting this output.. whats wrong??
for(int i{0}; i < size; i++)
{
int value {};
cout << "Enter value diagonal element " << i << " : ";
cin >> value;
setElement(f,i,i,value); //is this the correct way to send the function pointer?
}
}
///////////////////////////////////////////////////////////////////////////////
Main File
#include <iostream>
#include "MatrixOperations.h"
typedef MatrixOperations MATRIX;
using namespace std;
int main()
{
MATRIX m1;
m1.setMatrixTo(MATRIX::toDiagonalArray); //was expecting a "Hello there!" but i am not getting that output either
return 0;
}
EDIT2: I added all the class definitions and main function in one single file. SURPRISINGLY!! this works . I am confused??!!!
#include <iostream>
using namespace std;
class MatrixOperations;
typedef void (MatrixOperations::*VOIDFUNC)(int,int,int);
typedef MatrixOperations MATRIX;
class MatrixOperations
{
public:
MatrixOperations();
MatrixOperations(int size);
~MatrixOperations();
//diagonal matrix funtions
void setMatrixTo(VOIDFUNC f);
void setElement(VOIDFUNC to,int i ,int j, int value);
void toDiagonalArray(int i, int j, int value);
private:
int size;
int* a;
};
MatrixOperations::MatrixOperations()
{ //ctor
size = 3;
a = new int[size];
}
MatrixOperations::MatrixOperations(int size)
{ //ctor
this->size = size;
a = new int[size];
}
MatrixOperations::~MatrixOperations()
{
//dtor
delete[] a;
}
void MatrixOperations::setElement(VOIDFUNC to,int i ,int j, int value)
{
(this->*to)(i,j,value);
}
/////////////////////////////////DIAGONAL ARRAY OPERATIONS/////////////////////////////////////////////////
void MatrixOperations::toDiagonalArray(int i, int j, int value)
{
a[i] = value;
}
///////////////////////////////////////////////////////////////////
void MatrixOperations::setMatrixTo(VOIDFUNC f)
{
cout << "Hello there!!" << endl;
for(int i{0}; i < size; i++)
{
int value {};
cout << "Enter value diagonal element " << i << " : ";
cin >> value;
setElement(f,i,i,value);
}
}
int main()
{
MATRIX m1;
m1.setMatrixTo(MATRIX::toDiagonalArray);
return 0;
}
There is nothing wrong with the code in both cases. Its just my debugger was not running in admin mode. I got error code 740. So I launched my IDE in admin mode and voila it worked.

c++ segmentation fault trying to access vector

Im trying to create a adjacency representation of a graph.
I wrote a small program using vectors of vectors , however I keep getting "segmentation fault" but the compiler(clang++ version 5.0.1 on Windows) it seems wereever I try to access the vector vertex_matrix its giving a segmentation fault, why is it not being instantiated?
Here is the header:
#ifndef GRAPH_MATRIX
#define GRAPH_MATRIX
#include <vector>
//header for graph represented via adjacency matrix with minimal functionality
class graph
{
public:
graph(int);
~graph();
void add_edge(int v1, int v2, int weight);
void print_graph();
private:
std::vector<std::vector<int>> vertex_matrix;
int num_of_vertices;
int num_of_edges;
};
#endif
Here is the cpp implementation:
#include <iostream>
#include "graph_matrix.h"
#include <climits>
using namespace std;
//header for graph represented via adjacency matrix with minimal functionality
graph::graph(int _num_of_vertices) : num_of_vertices(_num_of_vertices)
{
if (_num_of_vertices==0)
{
_num_of_vertices=10;
}
for (int i = 0; i < _num_of_vertices; i++)
{
vertex_matrix[i]=(vector<int> (_num_of_vertices,INT_MAX));
}
}
graph::~graph()
{
vertex_matrix.clear();
}
void graph::add_edge(int v1, int v2, int weight)
{
//vertex_matrix[v1-1][v2-1] == INT_MAX
vector<int> columnVector = vertex_matrix[v1-1];
if (columnVector[v2-1] == INT_MAX)
{
columnVector[v2-1] = weight;
}
}
void graph::print_graph()
{
cout << "vertex_matrix size:" << vertex_matrix.size() << endl;
for (int i=0; i< num_of_vertices; i++)
{
for (int j = 0; j < num_of_vertices; j++)
{
//vertex_matrix[i][j]
std::vector<int> columnVector = vertex_matrix[i];
if (columnVector[j] != INT_MAX)
{
std::cout << columnVector[j] ;
}
else
{
std::cout << "0";
}
}
std::cout << endl;
}//end for printing
}
Here is the main entry:
#include <iostream>
#include "graph_matrix.h"
using namespace std;
int main ()
{
std::cout << " Matrix representation of graph" << std::endl;
graph _graph(4);
_graph.add_edge(1,2,1);
_graph.add_edge(2,3,1);
_graph.add_edge(3,1,1);
_graph.add_edge(3,3,1);
_graph.add_edge(3,4,1);
_graph.add_edge(4,0,0);
_graph.print_graph();
}
I edited the above code to use pass by reference, however the matrix still prints as 0's.
Please help with pass by reference, updates below:
Header:
#ifndef GRAPH_MATRIX
#define GRAPH_MATRIX
#include <vector>
//header for graph represented via adjacency matrix with minimal functionality
class graph
{
public:
graph(int);
~graph();
void add_edge(int v1, int v2, int weight,std::vector<std::vector<int>> & matrix);
void print_graph();
std::vector<std::vector<int>> vertex_matrix;
private:
int num_of_vertices;
int num_of_edges;
};
#endif
Cpp file:
#include <iostream>
#include "graph_matrix.h"
#include <climits>
using namespace std;
//header for graph represented via adjacency matrix with minimal functionality
graph::graph(int _num_of_vertices) : num_of_vertices(_num_of_vertices) {
if (num_of_vertices == 0) {
num_of_vertices = 10;
}
for (int i = 0; i < num_of_vertices; i++) {
std::vector<std::vector<int>>& matrix = vertex_matrix;
matrix.push_back(vector<int> (num_of_vertices, INT_MAX));
}
}
graph::~graph() {
std::vector<std::vector<int>>& matrix = vertex_matrix;
matrix.clear();
}
void graph::add_edge(int v1, int v2, int weight,std::vector<std::vector<int>> & _matrix) {
//vertex_matrix[v1-1][v2-1] == INT_MAX
vector<int> columnVector = _matrix[v1 - 1];
if (columnVector[v2 - 1] == INT_MAX) {
columnVector[v2 - 1] = weight;
}
}
void graph::print_graph() {
std::vector<std::vector<int>>& matrix = vertex_matrix;
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix.size(); j++) {
//vertex_matrix[i][j]
std::vector<int> columnVector = matrix[i];
if (columnVector[j] != INT_MAX) {
std::cout << columnVector[j];
} else {
std::cout << "0";
}
}
std::cout << endl;
}//end for printing
}
main:
#include <iostream>
#include "graph_matrix.h"
using namespace std;
int main ()
{
std::cout << " Matrix representation of graph" << std::endl;
graph _graph(4);
std::vector<std::vector<int>>& m = _graph.vertex_matrix;
_graph.add_edge(1,2,1,m);
_graph.add_edge(2,3,1,m);
_graph.add_edge(3,1,1,m);
_graph.add_edge(3,3,1,m);
_graph.add_edge(3,4,1,m);
_graph.add_edge(4,0,0,m);
_graph.print_graph();
}
Any help will be appreciated.
Thanks
You create an empty vector and then try to access elements in it. Change your constructor to
graph::graph(size_t _num_of_vertices) :
vertex_matrix(
std::vector<std::vector<int>>(
_num_of_vertices,std::vector<int>(_num_of_vertices)
)
)
{}
to create a correctly sized vector.
Also in case _num_vertices == 0 you set it to 10 but thats after you initialized the member num_vertices so you leave the object in an inconsistent state. There are different ways to fix that, I would probably just throw an exception when the number of vertices passed is zero, or just ignore it. User wants a zero sized matrix? Why not?
Moreover the size should be unsigned not signed, there is size_t for container sizes. Even better you shouldnt have that member at all, because a vector already knows its size, the only reason to repeat that information is to introduce mistakes ;)

C++ Vectors in a Class

i am working on a worksheet i have for university and the question asks me to "Allow a user to enter 10 numbers from the keyboard into an array" however we have been told that we need to use classes and vectors for this task. When i run my code i get an error stating: "Expression: Vector subscript out of range"
can anyone help?
Array.h
#include <iostream>
#include <vector>
using namespace std;
class Array
{
private:
vector<int> lists;
public:
void fillArray();
void printForwards();
void halfandHalf();
void shiftArrayRight();
Array();
Array(vector<int>);
};
Array.cpp
#include "Array.h"
Array::Array()
{
lists[10];
}
Array::Array(vector<int> lists)
{
this->lists = lists;
}
void Array::fillArray()
{
for (int i = 0; i < 10; i++)
{
cin >> lists[i];
}
}
void Array::printForwards()
{
for (int i = 0; i < 10; i++)
{
cout << lists[i];
}
}
Source.cpp
#include <iostream>
#include "Array.h"
using namespace std;
int main()
{
Array list1,list2;
//fill array 1
list1.fillArray();
//fill array 2
list2.fillArray();
// print array 1
list1.printForwards();
//print array 2
list2.printForwards();
system("pause");
return 0;
}
Thanks in advance
lists[10]; is not going to create a vector of size 10. It is going to try and access the 11th element of an empty vector. If you wanted to create a vector of size 10 then you can use
Array::Array() : lists(std::vector<int>(10, 0)) {}
I would also suggest you change
Array::Array(vector<int> lists)
{
this->lists = lists;
}
To
Array::Array(vector<int> lists) lists(lists) {}
You should also change your for loops to use the vector size() instead of a hard coded value
void Array::fillArray()
{
for (int i = 0; i < lists.size(); i++) // uses size()
{
cin >> lists[i];
}
}
void Array::printForwards()
{
for (int i = 0; i < lists.size(); i++) // uses size()
{
cout << lists[i];
}
}
Or if you have C++11 or higher you can use a ranged based for loop like
void Array::fillArray()
{
for (auto& e : lists)
{
cin >> e;
}
}
void Array::printForwards()
{
for (const auto& e : lists)
{
cout << e;
}
}

c++: vector of class instances, search by class member values failed

I have the following program where I defined a vector of class Point. I pushed into this vector five Point instances, with their Ids. Then I tried to search by Id but didn't get the expected result. The following program didn't return anything.
#include<iostream>
#include<vector>
using namespace std;
class Point {
private:
int id;
public:
Point(){}
void setId(int k){ id=k; }
int GetId() { return id; }
};
int main()
{
vector<Point> datasets;
for(int i=0; i< 5; ++i){
Point temp;
temp.setId(i);
datasets.push_back(temp);
}
for(int i=0;i<5;i++){
if (datasets[i].GetId() ==4){
return i;
}
}
}
Your program is probably working just fine, I think you're mixing up return with cout to actually print it out to the console, currently you're not printing anything and you're just returning i to the OS because you use return in main, making it a status code.
To see the output, use cout:
#include<iostream>
#include<vector>
using namespace std;
class Point{
private:
int id;
public:
Point(){}
void setId(int k){id=k;}
int GetId(){return id;}
};
int main()
{
vector<Point> datasets;
for(int i=0; i< 5; ++i){
Point temp;
temp.setId(i);
datasets.push_back(temp);
}
for(int i=0;i<5;i++){
if (datasets[i].GetId() ==4){
cout << "i is : " << i << endl;
break;
}
}
}
Edit to answer OP's comment:
use : vector<Point> datasets(5);
you arent printing any thing because you put return i after for loop
its certain that you wont got any result
#include<iostream>
#include<vector>
using namespace std;
class Point{
private:
int id;
public:
Point(){}
void setId(int k){id=k;}
int GetId(){return id;}
};
int main()
{
vector<Point> datasets;
for(int i=0; i< 5; ++i){
Point temp;
temp.setId(i);
datasets.push_back(temp);
}
for(int i=0;i<5;i++){
if (datasets[i].GetId() ==4){
cout<<i<<endl;
}
}
system("pause");
return 0;
}
you can use : datasets.insert(datasets.begin()+i,temp);
instead of datasets.push_back(temp);
for more flexibility in adding elements at the index i in vector class

Cannot convert 'double (*)[5]' to 'double' in return

I was wondering why do I keep getting an error and unable to return an array;
also, once the sell_item function actually work and return an array..how do I echo that array from the main function.
thanks
#include <iostream>
#include <fstream>
using namespace std;
ifstream infile;
ofstream outfile;
int itemnum = 3333;
string itemName="Cooking Range";
int Qauntity=1;
int NumberOfItems=2;
int NumberOfFields=5;
double function_Sell_Item(int itemnum,string itemName, int Qauntity);
int main () {
function_Sell_Item(itemnum, itemName, Qauntity);
}
double function_Sell_Item(int itemnum,string itemName, int Qauntity) {
double arraylist[2][5];
for (int index =0; index < NumberOfItems; index++) {
for (int i=0; i < NumberOfFields; i++) {
arraylist[index][i]=0;
}
}
return arraylist;
}
//// functions ends
:
;
You're trying to return an array, which you cannot do in C++.
You should consider something like std::vector<double>, because you can return that.
typedef std::vector<double> MyVec;
MyVec foo() {
MyVec v;
v.push_back(3.142);
v.push_back(2.718);
return v;
}
int main() {
MyVec z = foo();
for (int i = 0; i < z.size(); i++) {
std::cout << z[i] << "\n";
}
return 0;
}
Your code wont work at all as you return a local array, whose memory is not valid anymore after function return. You have to allocate the memory for the array dynamically on the heap.
Furthermore you have to change the return type of your function to double **
You are trying to return a double array (two-dimensional) which you can't in C++.
Use Vector instead!