Created
May 4, 2024 12:43
-
-
Save john9francis/7b236276f779f5594998f849a649792c to your computer and use it in GitHub Desktop.
Use case for std::map: counting instances of something
This file contains hidden or 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
#include <iostream> | |
#include <string> | |
#include <map> | |
#include <vector> | |
int main() | |
{ | |
// a map is a really good way to keep track of information. | |
// if the key doesn't exist, it will be created. | |
// if the key does exist, it will just reassign the value | |
// or add one to the value. | |
std::map<std::string, int> myMap; | |
myMap["hello"] = 1; | |
myMap["hello"]++; | |
myMap["world"]++; | |
for (auto i=myMap.begin(); i!=myMap.end(); i++ ){ | |
std::cout << i->first << ", " << i->second << std::endl; | |
} | |
// output: | |
// hello, 2 | |
// world, 1 | |
myMap.clear(); | |
// example: word counter | |
std::vector<std::string> words = {"foo", "bar", "foo", "hello", "world", "foo", "bar", "world", "foo"}; | |
for (const auto& word : words) { | |
myMap[word]++; | |
} | |
for (auto i=myMap.begin(); i!=myMap.end(); i++ ){ | |
std::cout << i->first << ", " << i->second << std::endl; | |
} | |
// output: | |
// bar, 2 | |
// foo, 4 | |
// hello, 1 | |
// world, 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment