By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,664 Members | 1,652 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,664 IT Pros & Developers. It's quick & easy.

How do I deallocate memory from a hash_map?

P: 2
Hi there,

I would much appreciate your help with the following problem.
Below is the code that uses a hash_map. I want to release all the memory occupied by the hash_map for other use. Apparently clear() function is not working and the trick with swap() is half working. Does anybody know how to deallocate the hash_map? Thanks in advance.


#include <functional>
#include <numeric>
#include <iomanip>
#include <algorithm>
#include <utility>
#include <climits>
#include <ext/hash_map>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iterator>
#include <iostream>

using namespace std;

using namespace __gnu_cxx;

typedef pair <int, int> Coordinates;

namespace __gnu_cxx
struct hash <Coordinates>
size_t operator()(const Coordinates& c) const
return (c.first << 24) + c.second;

typedef hash_map <Coordinates , double> HASH_MATRIX;

constructHashMatrix(HASH_MATRIX& hashMatrix,
const int& i,
const int& j,
const double& value) {
// create a pair
Coordinates ij(i,j);
// search for the pair in the table
// Coordinates i,j already exist. Locate this record and add to its current value
hash_map <Coordinates , double>::iterator pos = hashMatrix.find(ij);
if (pos == hashMatrix.end()) {
hashMatrix[ij] = value;
else {
pos->second += value;

main() {
char hold;

HASH_MATRIX::iterator p;
// fill in the hash matrix
int n = 200000;
for (int i = 0; i < n; i++) {
for (int j = 0; j < 10; j++) {
double value = 3.14;
constructHashMatrix(HM, i, j, value);
// at this stage I use about 70MB memory
cout << " Hash matrix constructed: Press enter to continue : " << endl;

// at this stage I use again about 70MB memory
cout << " Hash matrix clear() : Press enter to continue : " << endl;

// Swap trick to clear and get rid of capacity, too

hash_map <Coordinates , double>().swap( HM );
// at this stage I use again about 46MB memory

cout << " Hash matrix deallocated : Press enter to continue : " << endl;

// however, I want to release all the memory from the hash_map

return 0;
Oct 30 '06 #1
Share this Question
Share on Google+
3 Replies

P: 73
U can put ur code in a "{}" that will work.
Oct 30 '06 #2

P: 2
U can put ur code in a "{}" that will work.
You can try that yourself. It is not working, it releases abot 30% of occupied memory. I am solving huge system of equations and memory management is important. So if you know some other trick I'll greatly appreciate your help.

Nov 1 '06 #3

P: 73
This seems as if the memory pool did not return the memory back. U may try impl ur Alloc for ur hash map.
Nov 1 '06 #4

Post your reply

Sign in to post your reply or Sign up for a free account.