简体   繁体   中英

C implementation difference between map and unorderd_map

I'm rewriting a little C++ program to plain C, it's pretty trivial program which counts occurence of words in input using map . I'm using hashtable (structure containing size and array of pointers to linked node lists) of static size. I'm having trouble with rewriting following part to C

#if 1       // switch between 1 and 0
# include <tr1/unordered_map>
  typedef std::tr1::unordered_map<std::string,int>  map_t;
#else
# include <map>
  typedef std::map<std::string,int>  map_t;
#endif

I have primarily implemented the unordered version using the hash function, I used it this way

#if 1    // switch between 1 and 0
    int hash_function(const char *key, int size);
#else
    #define hash_function(key, size) .......
#endif

but now I have no idea how should the macro look like since I want the table to be ordered and I have static size of the table. Because I have no experience with maps I don't know if there is any conventional way of implementing this.

I got an idea of using the table as 2 dimensional array, as simple matrix, and filling it column by column from top to bottom.

So again, is there any better, conventional way, of doing this?

A pretty typical implementation of an ordered hashmap is just a regular hashmap with an additional linked list that goes through all the elements in order. The trick is to maintain this linked list correctly with every insertion and removal. The hash function doesn't (need to) change b/w and ordered and an unordered hashmap.

The main problem with your 2d array idea is that it consumes n*sizeOfHashTable space, most of which is wasted.

If you are implementing a sorted map, you usually take any ordered data structure like binary search tree and just let the keys (which are what you sort on) also have values associated with them. Then you don't use a hash function at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM