Created
October 22, 2022 20:53
-
-
Save classmember/ec79e9cc200b8c6cae96e242bc61bcd3 to your computer and use it in GitHub Desktop.
Hashmaps in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* phoneBook.cpp: | |
* Hashmaps in C++ - Kolby Heacock | |
* | |
* build: | |
* clang++ -std=c++2a test.cpp -o phonebook | |
* | |
* run: | |
* ./phonebook < input | |
* | |
* reference: | |
* https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem | |
*/ | |
#include <algorithm> | |
#include <climits> | |
#include <cmath> | |
#include <cstdio> | |
#include <iostream> | |
#include <unordered_map> | |
#include <sstream> | |
#include <string> | |
#include <cstring> | |
#include <vector> | |
using namespace std; | |
int main() { | |
unordered_map<string, string> phoneBook; | |
char line[USHRT_MAX]; | |
unsigned long lineNumber = 0; | |
unsigned long entries = 0; | |
unsigned long queries = 0; | |
unsigned long wordNumber = 0; | |
while (cin) { | |
if (cin.getline(line, USHRT_MAX)) { | |
++lineNumber; | |
if (lineNumber == 1) { | |
// Read number of entries | |
entries = stoi(line); | |
} else if (lineNumber <= 1 + entries) { | |
// Populate phone book | |
char *word = strtok(line, " "); | |
string key = ""; | |
string value = ""; | |
while (word != NULL) { | |
++wordNumber; | |
if (wordNumber == 1) { | |
key = word; | |
} else if (wordNumber == 2) { | |
value = word; | |
} | |
word = strtok(NULL, " "); | |
} | |
wordNumber = 0; | |
if(key != "" && value != "") { | |
phoneBook.insert({key, value}); | |
} | |
} else { | |
// Filter phoneBook by queries | |
if (phoneBook.find(string(line)) != phoneBook.end()){ | |
cout << line << "=" << phoneBook[line] << endl; | |
} else { | |
cout << "Not found" << endl; | |
} | |
} | |
} | |
} | |
// Display phone book | |
/* | |
for (auto i = phoneBook.begin(); i != phoneBook.end(); ++i) { | |
cout << i->first << " = " << i->second << endl; | |
} | |
*/ | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment