LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 12-21-2005, 06:24 AM   #1
gecoool
Member
 
Registered: Feb 2005
Location: Romania
Distribution: Fedora 2
Posts: 38

Rep: Reputation: 15
hash_map


please help. i want to insert some elements in a hash map like this:

#include <iostream>
#include <ext/hash_map>
#include <functional>

using namespace __gnu_cxx;
using namespace std;

typedef hash_map< string, int, hash<string>, equal_to<string> > map_type;
int main()
{
map_type m;
string kk = "mykey";
int vv = 2;
m[kk] = vv; // <= error here ...
return 0;
}

the code above doesn't even compile. What am I doing wrong here ? please advice me.
 
Old 12-21-2005, 12:11 PM   #2
YetAnotherDave
Member
 
Registered: Feb 2005
Posts: 95

Rep: Reputation: 17
The reason the code does not compile as is is that the hash<> template is fairly limited and will not apply to the std::string type. The following code includes a string hasher that fixes the compile problem.

Code:
#include <iostream>
#include <ext/hash_map>
#include <functional>

using namespace __gnu_cxx;
using namespace std;

struct hashstr
{
    size_t operator()(const string& s) const
    {
        hash<const char*> H;
        return H(s.c_str());
    }
};


typedef hash_map< string, int, hashstr, equal_to<string> > map_type;
int main()
{
    map_type m;
    string kk = "mykey";
    int vv = 2;
    m[kk] = vv; // <= error here ...
    return 0;
}
 
Old 01-08-2006, 05:34 AM   #3
gecoool
Member
 
Registered: Feb 2005
Location: Romania
Distribution: Fedora 2
Posts: 38

Original Poster
Rep: Reputation: 15
Thx

Thx YetAnotherDave. It worked !
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 04:08 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration