I would like to see a hash_map example in C++

前端 未结 5 780
广开言路
广开言路 2020-12-08 03:41

I don\'t know how to use the hash function in C++, but I know that we can use hash_map. Does g++ support that by simply including #include

相关标签:
5条回答
  • 2020-12-08 04:18

    The name accepted into TR1 (and the draft for the next standard) is std::unordered_map, so if you have that available, it's probably the one you want to use.

    Other than that, using it is a lot like using std::map, with the proviso that when/if you traverse the items in an std::map, they come out in the order specified by operator<, but for an unordered_map, the order is generally meaningless.

    0 讨论(0)
  • 2020-12-08 04:21

    #include <tr1/unordered_map> will get you next-standard C++ unique hash container. Usage:

    std::tr1::unordered_map<std::string,int> my_map;
    my_map["answer"] = 42;
    printf( "The answer to life and everything is: %d\n", my_map["answer"] );
    
    0 讨论(0)
  • 2020-12-08 04:29

    hash_map is a non-standard extension. unordered_map is part of std::tr1, and will be moved into the std namespace for C++0x. http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B%29

    0 讨论(0)
  • 2020-12-08 04:34

    Wikipedia never lets down:

    http://en.wikipedia.org/wiki/Hash_map_(C%2B%2B)

    0 讨论(0)
  • 2020-12-08 04:41

    The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":

    #include <unordered_map>
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        unordered_map <string, int> m;
        m["foo"] = 42;
        cout << m["foo"] << endl;
    }
    

    In order to get this compile, you need to tell g++ that you are using C++0x:

    g++ -std=c++0x main.cpp
    

    These maps work pretty much as std::map does, except that instead of providing a custom operator<() for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.

    0 讨论(0)
提交回复
热议问题