vendredi 5 juillet 2019

How to use iterators over unordered maps correctly? Why is this for-loop not running?

I need your help because I cannot move on.

I habe an unordered map:

 std::unordered_map <std::string, int> patterns;

This is a class attribute.

and I just want to iterate over it.

But the for loop with the defined iterator starts but do not execute code sequences in the code block of the for loop. Why?

I have already tried to reduce the code inside the for loop to a simple print statement, but even though it does not execute anything inside the for loop. The map should not be empty, because I can print the map out to console after I read in all patterns.

void count_words()
{

    for(std::unordered_map<std::string, int>::iterator it = 
        patterns.begin(); it != patterns.end(); ++it)
    {   
        std::cout << "Inside this for loop" << std::endl;
    }
}

And this is the code of the function, which reads in all the patterns.

void read_patterns()
{
    std::string pattern;
    while(getline(fhandle, pattern))
    {
        patterns.insert(std::pair<std::string, int> (pattern, 0));
    }
}

Gdb debugger with setting breakpoints showed this:

 Thread 1 "a" hit Breakpoint 1, FileParser::count_words (this=0xffffc700) 
 at FileParser.cpp:132
 132             for(std::unordered_map<std::string, int>::iterator it = 
                  patterns.begin(); it != patterns.end(); ++it)
 (gdb) n
 142         }
 (gdb) n
 main (argc=3, argv=0xffffcc00) at FileParser.cpp:168

Aucun commentaire:

Enregistrer un commentaire