Search code examples
c++hashhashmaphashtable

Hashing words in C++?


I have a text file that I read the data from and search the names inside to keep track of it. I want to use Hashing instead of Arrays for the speed of search, and I don't want to insert a name twice if it's already included in the hash.

(I found some code about hashing but the example code was for numbers not for strings or words. How should I approach? Keep the first letter in ASCII or combine all letters and % by a number? Not sure exactyle how to do it.)

Can you provide a short sample code if it's possible? Let's say; get every word in a text file with Getline and add it to Hash Table if the word is not included already.

Method does not matter (Chaining, linear probing etc.)

Please do not use any fancy library.


Solution

  • You can just use an unordered_set

    #include <string>
    #include <unordered_set>
    #include <fstream>
    
    std::unordered_set<std::string> file_to_unordered_set(const std::string& filename) {
        std::unordered_set<std::string> tbl;
        std::ifstream fs(filename);
        if (!fs) {
            throw std::runtime_error("bad file");
        }
    
        std::string line;
        while (std::getline(fs, line)) {
            tbl.insert(line);
        }
        return tbl;
    }
    
    int main() {
        auto words = file_to_unordered_set("<some file path>");
        return 0;
    }