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.
Kon
#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;
void
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;
}
}
int
main() {
char hold;
HASH_MATRIX HM;
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;
cin.get(hold);
// at this stage I use again about 70MB memory
HM.clear();
cout << " Hash matrix clear() : Press enter to continue : " << endl;
cin.get(hold);
// 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;
cin.get(hold);
// however, I want to release all the memory from the hash_map
return 0;
