Skip to content

Instantly share code, notes, and snippets.

@john9francis
Created May 4, 2024 12:43
Show Gist options
  • Select an option

  • Save john9francis/7b236276f779f5594998f849a649792c to your computer and use it in GitHub Desktop.

Select an option

Save john9francis/7b236276f779f5594998f849a649792c to your computer and use it in GitHub Desktop.

Revisions

  1. john9francis created this gist May 4, 2024.
    38 changes: 38 additions & 0 deletions map_counting.cc
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    #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
    }