0

I'm taking in a text file and putting the words into a vector. If the vector already contains the word, it will increment the occurance memeber. If it's a new word, we push it onto the vector. When I debug this, everything seems correct, but the vector is filled with every single word, with occurance = 1 because "i" seems to be one index behind.

If I initialize with i=1 though, the the vector will go out of range. Any help?

vector<wordFreq> words;

//already have 1 in vector, i initialized at 0.

while(!myfile.eof())
{

        myfile >> tempWord;                     //takes word into variable

        if (words[i].wordName == tempWord)      //if it is found
        {

            //words[i].occurances++;      //increment occurance member

        }
        else
        {
            //create new object
            wordFreq tempElement;
            tempElement.occurances = 1;
            tempElement.wordName = tempWord;
            words.push_back (tempElement);      //push onto vector

        }

        i++;
}
tshepang
  • 10,772
  • 21
  • 84
  • 127
Andrew Tsay
  • 1,543
  • 6
  • 18
  • 31
  • Please tag your language. – aliteralmind Mar 17 '14 at 02:21
  • To start off, this: `while(!myfile.eof())` [**is wrong.**](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). And if you have the latitude to use a [`std::map`](http://en.cppreference.com/w/cpp/container/map) or [`std::unordered_map`](http://en.cppreference.com/w/cpp/container/unordered_map) rather than just a vector, this becomes trivial quickly. – WhozCraig Mar 17 '14 at 02:37

2 Answers2

0

Change while(!myfile.eof()) myfile >> tempWord to

while ( myfile >> tempWord )

Otherwise you will get an extra loop iteration with a junk word.

Anyway, it sounds like you want to loop through the whole vector for each word to find this, e.g.:

int i;
for (i = 0; i < words.size(); ++i)
    if ( words[i] == tempWord )
    {
        ++words[i].occurances;
        break;
    }

if ( i == words.size() )   // not found
{
// create new object...
}

While this will work fine, there are standard algorithms that will do the job for you, specifically the find function. Check the documentation for find and see if you can replace your for loop with a find.

Finally, if you use a std::map instead of a vector than you can replace this entire block of code with ++my_map[tempWord].occurances;

M.M
  • 130,300
  • 18
  • 171
  • 314
0

Maybe a map can help you if you just want to count the words' occurance:

map<string, int> m;
string tempWord;
while (myfile >> tempWord) ++m[tempWord];

// print out
for (map<string, int>::const_iterator p = m.begin(); p != m.end(); ++p) {
    cout << p->first << '\t' << p->second << '\n';
}
songyuanyao
  • 147,421
  • 15
  • 261
  • 354