hash_map

Always there is problems with a hash_map, but google has a solution:

You must install "sparsehash" (apt-get install sparsehash)
The documentation is here: http://goog-sparsehash.sourceforge.net/

And here there is an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <google/sparse_hash_map>

using google::sparse_hash_map;      // namespace where class lives by default
using std::cout;
using std::endl;
using __gnu_cxx::hash;  // or ext::hash, or maybe tr1::hash, depending on your OS

struct eqstr
{
   bool operator()(const char* s1, const char* s2) const
   {
      return (s1 == s2) || (s1 && s2 && strcmp(s1, s2) == 0);
   }
};

int main()
{
     sparse_hash_map<const char*, int, hash<const char*>, eqstr> months;
     sparse_hash_map<const char*, int, hash<const char*>, eqstr>::iterator It;

     months.set_deleted_key(NULL);
     months["january"] = 31;
     months["february"] = 28;
     months["march"] = 31;
     months["april"] = 30;
     months["may"] = 31;
     months["june"] = 30;
     months["july"] = 31;
     months["august"] = 31;
     months["september"] = 30;
     months["october"] = 31;
     months["november"] = 30;
     months["december"] = 31;

     cout << "september -> " << months["september"] << endl;
     cout << "april     -> " << months["april"] << endl;
     cout << "june      -> " << months["june"] << endl;
     cout << "november  -> " << months["november"] << endl;

     /* Find and erase */
     It = months.find("january");
     if (It != months.end())
     {
        cout << "january found" << endl;
        cout << "erasing january" << endl;
        months.erase(It);
        if (months.find("january") == months.end())
            cout << "january erased" << endl;
        else
            cout << "january NOT erased" << endl;
     }
     else
        cout << "january NOT found" << endl;

     return 0;
}

Topic archived. No new replies allowed.