C++ What's wrong with my DFS code? - c++

I have tried to code the DFS algorithm as given in CLRS. Here's the code below. When I run it I got an error as "Your program stopped unexpectedly." When I debugged the code I got this line in the call stack "msvcrt!malloc()" and "operator new(unsigned int)". I'm using CodeBlocks. Where am I wrong?
#include<iostream>
#include<cstdlib>
#include<vector>
#include<list>
#include<utility>
#include<algorithm>
#include<string>
using namespace std;
struct prop
{
int p;
int value;
int d;
int f;
string color;
};
vector<prop>v;
prop make_prop(int a,int b,int c,int d,string e)
{
prop p = {a,b,c,d,e};
return p;
}
class Dfs
{
public:
int time;
vector<list<int> >adj;
Dfs(int nv)
{
v.resize(nv);
adj.resize(nv);
for(int i=0;i<nv;i++)
{
v[i].value = i;
v[i].p = -1;
v[i].color = "WHITE";
}
}
void addinput()
{
adj[0].push_back(1);
adj[0].push_back(2);
adj[0].push_back(3);
adj[1].push_back(0);
adj[1].push_back(3);
adj[2].push_back(0);
adj[2].push_back(3);
adj[3].push_back(0);
adj[3].push_back(1);
adj[3].push_back(2);
}
void dfs();
void dfsvisit(prop);
};
void Dfs::dfs()
{
time = 0;
for(int i=0;i<v.size();i++)
{
if(v[i].color == "WHITE")
{
dfsvisit(v[i]);
}
}
}
void Dfs::dfsvisit(prop m)
{
time++;
m.d = time;
m.color = "GRAY";
int val = m.value;
for(auto it = adj[val].begin();it != adj[val].end();it++)
{
if(v[*it].color == "WHITE")
{
v[*it].p = val;
dfsvisit(v[*it]);
}
}
m.color = "BLACK";
cout<<m.value;
time++;
m.f = time;
}
int main()
{
Dfs d(4);
d.addinput();
d.dfs();
return 0;
}

void Dfs::dfsvisit(prop m) // should be prop&
dfsvisit(prop m) will make a copy of the property while dfsvisit(prop& m) receives a reference, working directly on the property you passed to the function

the stack will overflow!
In function dfsvisit,you pass parameter by value,which will never change the actual parameter.You should pass parameter by reference.
void dfsvisit(prop& m);

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.

Arithmatic operator overloading in c++

#include<iostream>
using namespace std;
class money
{
int rs;
int p;
public:
void setdata (int x , int y)
{rs=x; p=y;}
void show()
{ cout <<rs <<"." <<p; }
money operator += (int a) {
money temp;
temp.rs=rs+a.rs;
temp.p=p+a.p;
return (temp);
}
};
int main() {
money c1,c2;
c1.setdata(8,2);
c2=c1.operator+=(4);
c2.show();
}
Can someone tell me why the operator += overloading doesn't work?
My desiring output is 12.2 but the output i got is 16.2 .
I am sending 4 as argument and i want this argument is added in r (ruppee)
part
#include<iostream>
using namespace std;
class money
{
int rs;
int p;
public:
void setdata (int x , int y)
{rs=x; p=y;}
void show()
{ cout <<rs <<"." <<p; }
money& operator+=(int a)
{ rs += a; return *this; }
};
int main() {
money c1,c2;
c1.setdata(4,2);
c2=c1+=(4); //c2=c1.operator+=(4);
c2.show();
}
Try to use constructor correctly.
For example:
#include <iostream>
using namespace std;
class Example
{
public:
int x;
Example(int a)
{
x=a;
}
Example operator+(Example obj)
{
Example ans(0);
ans=x+obj.x;
return ans;
}
};
int main()
{
Example a(10),b(20);
Example ans=a+b;
cout<<ans.x<<endl;
return 0;
}

for_each and mem_fun_ref trouble

I use for_each and mem_fun_ref as a example ,but there are some error in compile ,what's the problem
#include<iostream>
#include<algorithm>
#include<set>
#include<iterator>
using namespace std;
class Tst
{
public:
Tst(int a, string b):n(a),s(b)
{}
bool operator<(const Tst& t)const
{
return this->n < t.n;
}
int GetN()const
{
return n;
}
string GetS()const
{
return s;
}
void SetN(int a)
{
n = a;
}
void SetName(string name)
{
s = name;
}
void Print(void)
{
cout <<"n is:" << n <<"\ts is:" << s << endl;
}
private:
int n;
string s;
};
int main(void)
{
typedef set<Tst> TstSet;
TstSet tst;
tst.insert(Tst(10, "abc"));
tst.insert(Tst(1, "def"));
for_each(tst.begin(), tst.end(), mem_fun_ref(&Tst::Print));
return true;
}
:4200: 错误:对‘(std::mem_fun_ref_t) (const Tst&)’的调用没有匹配,是什么原因
std::set's contained objects are const, so you can only call const functions on them. Your Print function should be marked const.
The function should be const, because std::set only works with const objects
void Print(void)const
{
}

Function returning function pointer from table as a parameter

I have been reading for a while, but today I can't figure someting out and find a solution.
How to return a function pointer from a function table as parameter? All similair solutions don't work for this one and end up not compiling.
I have tried a lot of methods but the compiler always returns with errors like:
function returning function is not allowed solution (when using typedef void (*func)();)
As NO parameters have to be passed into the final routine it should be possible.
My simplified example:
void PrintOne(void) { printf("One")};
void PrintTwo(void) { printf("Two")};
struct ScanListStruct
{
int Value;
void (*Routine)(void);
}
const ScanListStruct DoList[] =
{
{1, PrintOne},
{2, PrintTwo}
}
bool GetRoutine(void *Ptr, int Nr)
{
for (int x =0; x<=1; x++)
{
if (DoList[x].Value = Nr)
{
Ptr = DoList[(x)].Routine;
//((*DoList[(x)].Routine)()); // Original Working and executing version!
return true;
}
}
return false;
}
void main(void)
{
int y = 1;
void (*RoutineInMain)(); // Define
if (GetRoutine( RoutineInMain, y) == true) // get the address
{
RoutineInMain(); // Execute the function
}
}
There a few things wrong with the code;
Syntax errors (missing ; etc.)
main must return int
GetRoutine should accept the function pointer by reference, not just a void* pointer to anything
if condition should contain an equality test, not an assignment
As follows, works as expected;
void PrintOne(void) { printf("One"); };
void PrintTwo(void) { printf("Two"); };
struct ScanListStruct
{
int Value;
void (*Routine)(void);
};
const ScanListStruct DoList[] =
{
{1, &PrintOne},
{2, &PrintTwo}
};
bool GetRoutine(void (*&Ptr)(), int Nr)
{
for (int x =0; x<=1; x++)
{
if (DoList[x].Value == Nr)
{
Ptr = *DoList[(x)].Routine;
//((*DoList[(x)].Routine)()); // Original Working and executing version!
return true;
}
}
return false;
}
int main(void)
{
int y = 1;
void (*RoutineInMain)(); // Define
if (GetRoutine( RoutineInMain, y) == true) // get the address
{
RoutineInMain(); // Execute the function
}
}
Prints One.
You have lots of errors in your code. Like here you put the comas at the wrong place:
void PrintOne(void) { printf("One")};
void PrintTwo(void) { printf("Two")};
It should be
void PrintOne(void) { printf("One");}
void PrintTwo(void) { printf("Two");}
And here you are using the wrong operator, = instead of ==.
if (DoList[x].Value = Nr)
When the argument Ptr is a pointer, and that is passed by value, so the value assigned in the function will not be available when the function returns.
This is how your code should be:
void PrintOne(void) { printf("One"); }
void PrintTwo(void) { printf("Two"); }
typedef void(*prototype)();
struct ScanListStruct
{
int Value;
prototype Routine;
};
const ScanListStruct DoList[] =
{
{ 1, PrintOne },
{ 2, PrintTwo }
};
bool GetRoutine(prototype &Ptr, int Nr)
{
for (int x = 0; x <= 1; x++)
{
if (DoList[x].Value == Nr)
{
Ptr = DoList[(x)].Routine;
return true;
}
}
return false;
}
int main()
{
int y = 1;
prototype RoutineInMain; // Define
if (GetRoutine(RoutineInMain, y) == true) // get the address
{
RoutineInMain(); // Execute the function
}
return 0;
}

Pass Vector by reference and Get Error

Following code is for test the pass the reference of a vector to a function. However, it will have some unknown fault. I got the error message from gdb as following:
Source is:
#include<iostream>
#include<vector>
using namespace std;
class ROLE
{
public:
ROLE(int);
int HP;
};
ROLE::ROLE (int input)
{
HP = input;
}
void checkVector(vector<ROLE>&input);
int main()
{
vector<ROLE> R;
ROLE K(102);
R.push_back(K);
K.HP = 111;
R.push_back(K);
checkVector(R);
return 1;
}
void checkVector(vector <ROLE> & input)
{
cout<<"size of vector "<<input.size()<<endl;
for(int i =0; i<input.size();i++)
{
cout<< input[i].HP<<endl;
}
}
I can't find the reason of the error. Any idea is appreciated!
I realized that error probably from the push_back, because I also get the error if I modified the code as following. Are there any idea about what happened?
#include<iostream>
#include<vector>
using namespace std;
class ROLE
{
public:
ROLE(int);
int HP;
};
ROLE::ROLE (int input)
{
HP = input;
}
int main()
{
vector<ROLE> R;
ROLE K(0);
K.HP=1;
R.push_back(K);
K.HP = 113;
R.push_back(K);
K.HP = 111;
R.push_back(K);
return 0;
}
Possible answer:
I get one way which can avoid the error.
Following is the no-error source.
#include<iostream>
#include<vector>
using namespace std;
class ROLE
{
public:
ROLE(int);
void constructAry(int inputHP);
int HP;
};
ROLE::ROLE (int input)
{
HP = input;
}
void ROLE::constructAry(int inputHP)
{
HP = inputHP;
}
void checkVector(vector<ROLE>&input);
int main()
{
vector<int> test;
vector<ROLE> R;
ROLE K(0);
K.constructAry(1);
R.push_back(K);
K.constructAry(2);
R.push_back(K);
K.constructAry(3);
R.push_back(K);
K.constructAry(4);
R.push_back(K);
checkVector(R);
return 1;
}
void checkVector(vector <ROLE> & input)
{
cout<<"size of vector "<<input.size()<<endl;
for(int i =0; i<input.size();i++)
{
cout<< input[i].HP<<endl;
}
}
So it seems that using a constructor-like function to modify the value of the same object and push_back the object in the vector can effectively avoid the bug.
The reason is ambiguous for me. Maybe the memory address's matter.