Question

I have a std::map declared thusly in a legacy MFC application:

typedef std::map<long, CNutrientInfo> NUTRIENT_INFO_MAP;
typedef NUTRIENT_INFO_MAP::const_iterator NUTRIENT_INFO_ITER;
typedef NUTRIENT_INFO_MAP::value_type NUTRIENT_INFO_PAIR;
static NUTRIENT_INFO_MAP m_NutrientInfoMap;

m_NutrientInfoMap is populated when the app loads by looping through a table and creating an instance of CNutrientInfo and then inserting it into the std:map like:

m_NutrientMapInfo.insert(NUTRIENT_INFO_PAIR(nutrient.GetId(), nutrient));

The std::map now contains a list of the nutrients that have been defined by the database. At some point a user can add a new nutrient to this list and it checks to see if what the user is adding already exists in the list. It does that check like:

NUTRIENT_INFO_ITER iter = m_NutrientInfoMap.begin();
while (iter != m_NutrientInfoMap.end())
{
    m = (*iter).second;
    if (_stricmp(m.GetFullName().c_str(), name.c_str()) == 0)
    {
        return m;
    }
    iter++;
}

Or at least it's supposed to. When the function actually gets called it never advances past the initial line of the while loop. Placing a breakpoint there simply shows that the line in question is called over and over and never advances beyond it, which hangs the app. If you step into the actual comparison it compares correctly and then returns to the while loop line. Stepping in again to advance into the body of the loop simply returns to the while loop line. This same logic is used elsewhere in the app with no trouble so I'm stumped as to what's going on in this case. I've re-written the logic above using a for-loop and it works just fine, so it's not like I can't work around it, but C++ isn't my strongest language and as this is a legacy app that I'm trying to help support, I'd really like to learn and understand WHY this is doing what's it's doing for future reference. Plus, since the logic works elsewhere and not here perhaps there's an underlying cause that is what actually needs to be addressed.

Any suggestions or thoughts on this would be greatly appreciated.

Thanks in advance.

Was it helpful?

Solution

Is your example actually pasted from the source? Maybe it looks more like:

while (iter != m_NutrientInfoMap.end());   // <== note the semi-colon
{
    m = (*iter).second;
    if (_stricmp(m.GetFullName().c_str(), name.c_str()) == 0)
    {
        return m;
    }
    iter++;
}

OTHER TIPS

There is nothing in the code posted above which can cause that behavior. Are you sure that you are incrementing some other iterator inside the loop or may be there two iterators with the same name (one inside the loop) with different scopes and you are incrementing the wrong iterator ? If this is not the case, then only other alternative I could see is to note down the value of m_NutrientInfoMap.end() and check why ++iter is not evaluating into that value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top