mobo
mobo

Reputation: 301

Differences in iterating through a C++ map

First

I have a class Node that contains a draw function. Nodes are contained in a map such as:

map<std::string, Node*>

When I use an iterator to draw all of the nodes in the map nothing happens. (gc is the graphical context I pass to the draw function)

std::map<std::string, Node*>::const_iterator itr = _Nodes.begin();
while(itr != _Nodes.end())
{
    itr->second->setX(100);
}

But that doesn't work. However if I construct my iterator differently it works.

std::map<std::string, Node*>::const_iterator end = _Nodes.end();
for(std::map<std::string, Node*>::const_iterator it = _Nodes.begin(); it != end; ++it){
    it->second->draw(gc);
    it->second->setSize(100);
}

My question is why does one work and not the other?

Second question is what would an be alternate way to store all of the nodes in the NodeManager class without having to name them? Just a simple list?

Upvotes: 0

Views: 209

Answers (2)

iammilind
iammilind

Reputation: 69988

--> But that doesn't work.

Because there are major difference between the 1st version (while loop) and 2nd version (for loop).

  1. while() doesn't have any it++ for increasing iterator
  2. In while() you call only setX()

--> what would an be alternate way to store all of the nodes in the NodeManager class without having to name them?

May be you are looking for,

  1. std::vector (or equivalents), if you want simply an array
  2. std::set, if you want to be able to find a node based on Node*

Upvotes: 4

J.N.
J.N.

Reputation: 8421

You are not calling ++itr in the first loop. Your iterator will never change.

Should be:

std::map<std::string, Node*>::const_iterator itr = _Nodes.begin(); 
while(itr != _Nodes.end()) 
{ 
    itr->second->setX(100); 
    ++itr;
} 

PS : if you can use C++11, this is much more convenient:

auto itr = _Nodes.begin();

PPS: _Node is a forbidden name. Names beginning in underscore + capital are reserved by the standard.

PPPS: In the first example you proably want to store end() in a variable to store a little bit of performance (but very little).

Upvotes: 5

Related Questions