分配空间到list< int>使用malloc的指针不起作用 [英] allocating space to list<int> pointers using malloc not working
问题描述
class graph
{
int v;
list<int> *adj;
void dfsutil(int v,bool visited []);
public:
graph(int v)
{
this->v=v;
//adj = new list<int>[v];
adj = (list<int> *)malloc(v*sizeof(list<int>));
}
void addedge(int v,int w);
void dfs(int v);
};
void graph::addedge(int v,int w)
{
adj[v].push_back(w);
}
void graph::dfsutil(int v,bool visited[])
{
list<int>::iterator i;
cout<<v<<" ";
visited[v]=true;
for(i=adj[v].begin();i!=adj[v].end();i++)
{
if(!visited[*i])
dfsutil(*i,visited);
}
}
void graph::dfs(int v)
{
int i=0;
bool visited[this->v];
for(i=0;i<this->v;i++)
visited[i]=false;
dfsutil(v,visited);
for(i=0;i<v;i++)//this loop is required if there are multiple component of the graph
if(!visited[i])
dfsutil(i,visited);
}
int main()
{
// Create a graph given in the above diagram
graph g(4);
g.addedge(0, 1);
g.addedge(0, 2);
g.addedge(1, 2);
g.addedge(2, 0);
g.addedge(2, 3);
g.addedge(3, 3);
cout << "Following is Depth First Traversal (starting from vertex 2) \n";
g.dfs(2);
return 0;
}
在上面的代码中,如果尝试使用上面编写的malloc为列表* adj分配空间,则无法正常工作,而如果我们使用new,则如上面的注释部分所述,效果很好,我无法弄清楚为什么
in the above code if try to allocate space for list *adj using malloc as written above,it does not work fine whereas if we use new,it works fine as its written in commented part above,i cant figure out why
推荐答案
使用malloc
时没有创建std::list
对象的数组. malloc
所做的只是从堆中分配内存-不创建任何对象.因此,尝试像正确创建std::list
那样使用std::list
会导致不确定的行为.
You did not create an array of std::list
objects when you used malloc
. All malloc
does is allocate memory from the heap -- no objects are created. Thus attempting to use your std::list
's as if they are created correctly will result in undefined behavior.
您应该使用诸如std::vector
之类的容器来存储列表对象:
You should use a container such as std::vector
to store your list objects:
#include <vector>
#include <list>
class graph
{
int v;
std::vector<std::list<int>> adj;
void dfsutil(int v,bool visited []);
public:
graph(int num) : v(num), adj(num) {}
void addedge(int v,int w);
void dfs(int v);
};
请注意,无需分配内存.您的其余代码应保持不变,因为vector
具有重载的operator []
来访问项目.
Note there is no need to allocate memory. The rest of your code should stay the same, since vector
has an overloaded operator []
to access the items.
这篇关于分配空间到list< int>使用malloc的指针不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!