How to find the frequency of every word in a vector of strings with C++

2 Answers

0 votes
#include <iostream>
#include <unordered_map>
#include <sstream>
#include <vector>

void countWordFrequencies(const std::vector<std::string>& stringsarr) {
    std::unordered_map<std::string, int> wordCount;

    for (const auto& str : stringsarr) {
        std::istringstream stream(str);
        std::string word;
        while (stream >> word) {
            wordCount[word]++;
        }
    }

    for (const auto& pair : wordCount) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
}

int main() {
    std::vector<std::string> stringsarr = {
        "java",
        "c++",
        "c",
        "c#",
        "c",
        "go",
        "php",
        "java",
        "java",
        "c",
        "python",
        "php",
        "c" 
    };

    countWordFrequencies(stringsarr);
}

 
 
/*
run: 
 
python: 1
go: 1
c#: 1
c: 4
c++: 1
php: 2
java: 3
 
*/

 



answered Nov 24, 2024 by avibootz
0 votes
#include <iostream>
#include <unordered_map>
#include <sstream>
#include <vector>

std::unordered_map<std::string, int> countWordFrequencies(const std::vector<std::string>& stringsarr) {
    std::unordered_map<std::string, int> wordCount;

    for (const auto& str : stringsarr) {
        std::istringstream stream(str);
        std::string word;
        while (stream >> word) {
            wordCount[word]++;
        }
    }

    return wordCount;
}

int main() {
    std::vector<std::string> stringsarr = {
        "java",
        "c++",
        "c",
        "c#",
        "c",
        "go",
        "php",
        "java",
        "java",
        "c",
        "python",
        "php",
        "c" 
    };

    std::unordered_map<std::string, int> wordCount = countWordFrequencies(stringsarr);
    
    for (const auto& pair : wordCount) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
}

 
 
/*
run: 
 
python: 1
go: 1
c#: 1
c: 4
c++: 1
php: 2
java: 3
 
*/

 



answered Nov 24, 2024 by avibootz
...