As we all know we don't have Hashes in STL can anybody please suggest an analogous way of emulating it. Or also has any library added it as a standard component?

Please do let me know

Recommended Answers

All 8 Replies

Member Avatar for GreenDay2001

it is a standard component of the library in c++0x see http://www.open-std.org/jtc1/sc22/wg21/ libstdc++ (gcc 4.30) and dinkumware std c++ library implement this natively; boost.tr1 library could be used if you have an older compiler and boost.

#include <iostream>
#include <functional>

int main( int argc, char** argv )
{
  //using libstdc++ TR1 implementation (g++43 -std=c++0x)
  std::cout << std::hash<char*>()( argv[0] ) << '\n' ;

  //using boost.tr1 library ( #include <boost/tr1/functional.hpp> )
  //std::cout << std::tr1::hash<char*>()( argv[0] ) << '\n' ;
}

Hash tables (called unordered_map) are part of tr1, which is mostly being implemented for the next version of C++.

GCC has implemented most of tr1 and it happens to include an implementation of unordered_map. Here's an example mapping names (as std::string) to ages (as int).

I am not an expert, so I apologize in advance to the daniweb gurus if this code is incorrect in any way. :)

#include <string>
#include <iostream>

#include <tr1/unordered_map>

typedef std::tr1::unordered_map<std::string, int> AgeTable;

int main() {
    AgeTable ages;
    
    ages.insert( std::make_pair( "Joe", 25 ) );
    ages.insert( std::make_pair( "Sally", 18 ) );
    ages.insert( std::make_pair( "Billy", 11 ) );
    
    AgeTable::iterator iter;
    for ( iter = ages.begin(); iter != ages.end(); iter++ ) {
        std::cout << iter->first << " is " << iter->second << std::endl;
    }
}

while going thru STL I came to know something knows as functors. Thought I understood what practically it is but still could not make out it's advantage and usage. Could anybody throw some light over it. I need to know in detail about it.

while going thru STL I came to know something knows as functors. Thought I understood what practically it is but still could not make out it's advantage and usage. Could anybody throw some light over it. I need to know in detail about it.

This isn't related to hash, hope you know that. Ideally creation of a new thread for a new topic is helpful for everyone (rather than e.g. discussing all STL doubts in one thread).

See this link for description of functors AKA function objects or functionoid.

Just use a std::map. You hear me? A std::map. Do you have any good reason to do otherwise? You're probably overestimating the importance of the log n time factor (which hash tables usually still have, albeit in a hidden manner). Of course, maybe you really can't use a std::map for some reason. But I don't see why.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.