jezpez
jezpez

Reputation: 276

STL list<Object> iterator to change an object within the list

I'm an amateur so bear with me, but I've hit the end of my research with no solution for this.

This code complies fine but when I debug, it's apparent that the procedure exists upon reaching the for loop, and never executes what is within it (which is what I need to do).

void insertWord(list<Word> &words, string str)
{
    list<Word>::iterator itr;
    for (itr = words.begin(); itr != words.end(); itr++ ) //EXITS HERE
    {
        if (str == (*itr).aWord)
        {
            (*itr).iterateCount();
            return;
        }
        if (str > (*itr).aWord)
        {
            words.push_back(Word(str));
            return;
        }
    }
}

I don't understand why the for loop is never executed. It just skips right to the end of the function.

NB: "Word" is a custom class to hold a string and an int(how many of that string there are). If any more info is required please ask, I'm dying here! Thanks.

Upvotes: 2

Views: 1261

Answers (2)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24143

You could use a std::map:

std::map<Word, int> histogram;

histogram[Word("hello")] += 1;
histogram[Word("hello")]++; //  equivalent

histogram[Word("vertigo")]++;

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227458

It looks like your list is empty, so itr==words.end() and the code in the loop never executes.

Upvotes: 2

Related Questions