Too many entries in vector

I am writing a function that looks for a word in the vector, if it appears, I add a new appearance with the score. If not I push back the word with a score. My issue is if I expected my vector to have a size of 6 my program finishes with 7. I have tried adding and else if, nested for, and while loop but then it messes my vector up more with have more than one extra size. Any ideas would be helpful.

1
2
3
4
5
6
7
8
9
10
11
12
  void Entries::put(string word, int score) {

    //loops through vector
        for (int i = 0; i < data.size(); i++) {
            //if vector at i == word
            if (data.at(i).get_word() == word) {
                //add new appearance
                data.at(i).add_new_appearance(score);
            }
        }
        data.push_back(WordEntry(word, score));
}
Last edited on
Your push_back is executed regardless of whether the word occurs in the vector.

1
2
3
4
5
6
7
8
9
10
void Entries::put(string word, int score) {
    for (int i = 0; i < data.size(); i++) {
       if (data.at(i).get_word() == word) {
           data.at(i).add_new_appearance(score);
           return;   // we're done, get out of here.
        }
    }

    data.push_back(WordEntry(word, score));
}

Thank you so much. I knew it was something simple, I was right there. Just didnt think of doing a return.
Just didnt think of doing a return.


As they say, there's more than one way to skin a cat.

1
2
3
4
5
6
7
8
9
10
11
12
13
void Entries::put(string word, int score) {
    std::size_t i;       // move the state outside the scope of the for loop.

    for (i = 0; i < data.size(); i++) {
       if (data.at(i).get_word() == word) {
           data.at(i).add_new_appearance(score);
           break;   // we're done, get out of here.
        }
    }

    if ( i == data.size() )  
        data.push_back(WordEntry(word, score));
}
Topic archived. No new replies allowed.