Skip to content

Instantly share code, notes, and snippets.

@john9francis
Created May 4, 2024 12:43
Show Gist options
  • Save john9francis/7b236276f779f5594998f849a649792c to your computer and use it in GitHub Desktop.
Save john9francis/7b236276f779f5594998f849a649792c to your computer and use it in GitHub Desktop.
Use case for std::map: counting instances of something
#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