我寫了一個使用全局堆的代碼。我需要多次重做相同的操作。每次我需要清除堆並重新分配數據。但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