Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Please do not use any fancy library.

>Solution :

You can just use an unordered_set

#include <iostream>
#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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading