我已经使用全局堆编写了一个代码。我需要多次重做相同的操作。每次我需要清除堆并重新分配数据时。但是 vector::clear() 函数不会释放内存。所以一段时间后内存被填满并且程序终止。
#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() 函数。但这没有用。谁能帮助我如何释放“已清除”的内存空间?