I just do my homework using graph data structure and use heap memory and I want to clear that memory. My homework is about teachers want to know. How many vertexes that are even number by using Depth First Search. Why deconstructor run 2 times? It makes this program error because it's already deleted that memory.
#include<iostream>
#include <string.h>
struct graph
{
int vertex;
int edges;
int **martrix;
void setMartrix(int x,int y)
{
vertex=x;
edges=y;
martrix=new int*[vertex];
for(int i=0;i<vertex;i++)
martrix[i]=new int[edges];
for(int col=0;col<vertex;col++)
{
for(int row=0;row<edges;row++)
martrix[col][row]=0;
}
}
void add_edge(int edge1,int edge2)
{
martrix[edge1][edge2]=1;
martrix[edge2][edge1]=1;
}
void print()
{
for(int col=0;col<vertex;col++)
{
for(int row=0;row<edges;row++)
std::cout<<martrix[col][row]<<" ";
std::cout<<std::endl;
}
}
~graph()
{
std::cout<<"delete complete"<<std::endl;
for(int i=0;i<vertex;i++)
delete martrix[i];
delete martrix;
martrix=nullptr;
}
};
void findans(graph g)
{
int ans=0;
int visited[g.vertex];
memset(visited,0,sizeof(visited));
for(int col=0;col<g.vertex;col++)
{
for(int row=0;row<g.edges;row++)
{
if(g.martrix[col][row]== 1 && !visited[col])
{
// std::cout<<col+1<<" ";
visited[col]=1;
ans=((col+1)% 2 == 0)?
++ans:
ans;
}
}
}
// std::cout<<std::endl;
std::cout<<ans<<std::endl;
}
int main()
{
graph g;
int v,e;
std::cin>>v>>e;
g.setMartrix(v,e);
for(int i=0;i<v;i++)
{
int temp1,temp2;
std::cin>>temp1>>temp2;
g.add_edge(temp1-1,temp2-1);
}
findans(g);
return 0;
}
input:
5 7
1 2
1 3
1 5
2 5
2 4
3 5
4 3
output:
2
delete complete //this line I just check by print this line to find an error and founded it delete 2 times.
delete complete