我写了一个使用全局堆的代码。我需要多次重做相同的操作。每次我需要清除堆并重新分配数据。但vector :: clear()函数不释放内存。所以一段时间后内存被填满并且程序终止。错误:std :: bad_alloc在内存位置0x0038fd50
#include "stdafx.h"
#include <cstdio>
#include <vector>
using namespace std;
#define N 30000
typedef unsigned int uint;
class Node;
class Edge;
vector<Node*> nodes;
vector<Edge*> edges;
class Node
{
public:
Node(uint id): id(id)
{
nodes.push_back(this);
}
public:
uint id;
};
class Edge
{
public:
Edge(int nod1, int nod2)
: nodH(nod1), nodT(nod2)
{
edges.push_back(this);
}
bool Connects(Node* nod1, Node* nod2)
{
return (
(nod1->id == this->nodH && nod2->id == this->nodT) ||
(nod1->id == this->nodT && nod2->id == this->nodH));
}
public:
int nodH;
int nodT;
};
int _tmain(int argc, _TCHAR* argv[])
{
Node *nd;
for(long int i=0;i<N;i++)
{
for (int j=0;j<N;j++)
{
nd = new Node(j);
}
for (uint j=0;j<N;j++)
{
Edge* e = new Edge(j,N-j);
}
printf("%d %d ",nodes.size(),edges.size());
// Do something here like calling function etc.
nodes.erase(nodes.begin()+N/2);
nodes.clear();
edges.clear();
//nodes.~vector();
//edges.~vector();
printf("%d %d\n",nodes.size(),edges.size());
}
getchar();
return 0;
}
我该怎么办?我尝试了vector ::〜vector()函数。但那并不奏效。 任何人都可以帮我解释如何释放“清除”的内存空间吗?
我试过以下内容: \t \t \t ** vector temp_nod; \t \t \t vector temp_edg; \t \t \t swap(nodes,temp_nod); \t \t \t swap(edges,temp_edg); \t \t \t temp_nod。〜vector(); \t \t \t temp_edg。〜vector(); ** 但它仍然无法正常工作。 –
2013-03-22 10:10:33
无法理解哪些不起作用...是否要删除矢量(由Edge * e = new Edge(j,N-j);')创建的所有元素? – borisbn 2013-03-22 10:13:15
程序使用的内存仍在增加。 向量中的元素正在被删除。但内存空间并未被释放。 :( – 2013-03-22 10:20:11