Anxenon Anxenon - 2 months ago 11
C++ Question

How to count amount of unique elements in an array of structs?

I have a structure:

struct wordItem
{
string word;
int count;
};


I'm reading in a text file with many different words and storing them into an array.

ifstream inputFile("data.txt");
if(inputFile.is_open())
{
while(getline(inputFile, data, ' '))
{
wordItemList[i].word = data;
i++;
}
}


My question is what is the best way to count each time a word appears in the array. For example if my data.txt file was

the fox jumped over the fence


I want to be able to store how many times each word appears within the struct within the "int count;"

Answer
ifstream inputFile("data.txt");
if(!inputFile.is_open()) {
    cerr << "Can't open data.txt\n";
    exit(0);
}

map<string, int> freq;
while(getline(inputFile, word, ' '))
    ++freq[word];
Comments