Skip to content

Instantly share code, notes, and snippets.

@DragonOsman
Last active December 9, 2017 12:40
Show Gist options
  • Save DragonOsman/fe8f75466a69b2835d432bfbba0cd739 to your computer and use it in GitHub Desktop.
Save DragonOsman/fe8f75466a69b2835d432bfbba0cd739 to your computer and use it in GitHub Desktop.
A dictionary application using a std::unordered_map
// Osman Zakir
// 12 / 8 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 21 std::unordered_map "Try this"
// Exercise Specifications:
/**
* Write a small program using #include<unordered_map> . If that doesn’t
* work, unordered_map wasn’t shipped with your C++ implementation. If
* your C++ implementation doesn’t provide unordered_map , you have to
* download one of the available implementations (e.g., see www.boost.org).
*/
// Note: The version of the book I have is from when unordered_map wasn't in the standard
// proper yet, hence Stroustrup saying here that the reader's implementation
// might not provide it.
// This program uses the unordered_map hash table to implement a simple dictionary,
// using an unordered_map with input taken from a file of English words
#include <string>
#include <cctype>
#include <vector>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include "../../cust_std_lib_facilities.h"
int main()
{
std::unordered_map<char, std::vector<std::string>> dict;
std::ifstream ifs{ "words_alpha.txt" };
std::vector<char> char_table{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
for (std::string word; std::getline(ifs, word);)
{
for (auto iter = char_table.begin(); iter != char_table.end(); ++iter)
{
try
{
if (std::tolower(*iter) == std::tolower(word.at(0)))
{
dict[std::tolower(*iter)].push_back(word);
break;
}
}
catch (const std::out_of_range &oor)
{
std::cerr << oor.what() << '\n';
}
}
}
for (auto i = dict.begin(); i != dict.end(); ++i)
{
if (i->first == 'd' || i->first == 'D')
{
for (auto it = dict[i->first].begin(); it != dict[i->first].end(); ++it)
{
std::cout << *it << '\n';
}
}
}
keep_window_open();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment