return a map with each unique word as key code example

Example: store words of a string in map

int main()
{
    std::string input="Hello My name is OP Hello World";
    std::map<std::string, int> myMap;
    std::istringstream iss(input);
    while (iss) {
        std::string substr;
        std::getline(iss,substr,' ');
        int count = 0;
        auto pos = input.find(substr, 0);
        while (pos != std::string::npos) {
            ++count;
            pos = input.find(substr, pos + 1);
        }
        if(substr.size() != 0)
            myMap[substr] = count;
    }
    for (const auto &p : myMap) {
        std::cout << p.first << "=" << p.second << '\n';
    }
    return 0;
}

Tags:

Misc Example