user63898 user63898 - 3 months ago 25
C++ Question

Interleaving std::map insertion and iteration

If I iterate

std::map
like this:

typedef std::map<connection, connectionData> clist;
clist m_connections;

for (const auto itt : m_connections)
{
connectionData outerPlayerData = itt .second;
// Do stuff
}


and somewhere in the code the
m_connections
getting filled constantly, does it mean the iterating loop will run forever? Is it growing

or it will run the size of the
m_connections
in this point of time and the relevant size which was in that point of time?

Answer

It will iterate forever if you keep on adding constantly at position greater than the current iteration position. The elements keep on adding and the loop iteration considers the current status of map.

Demo

int main() {
    // your code goes here
    map<int, int> m;
    m.insert(make_pair(10, 11));
    int i = 0;
    for(auto it : m){
        cout << it.second << endl;
        if(i++ == 0){ 
            m.insert(make_pair(15, 12));
        }
    }
    return 0;
}

Gives output as:

11
12

NOT

11
Comments