简体   繁体   English

通过C ++映射进行迭代的差异

[英]Differences in iterating through a C++ map

First 第一

I have a class Node that contains a draw function. 我有一个包含绘图功能的类Node。 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) (gc是我传递给draw函数的图形上下文)

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? 只是一个简单的清单?

You are not calling ++itr in the first loop. 您不是在第一个循环中调用++itr 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: PS:如果可以使用C ++ 11,这将更加方便:

auto itr = _Nodes.begin();

PPS: _Node is a forbidden name. PPS: _Node是禁止的名称。 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). PPPS:在第一个示例中,您可能想将end()存储在变量中,以存储一点点性能(但很少)。

--> But that doesn't work. ->但这不起作用。

Because there are major difference between the 1st version ( while loop) and 2nd version ( for loop). 因为第一个版本( while循环)和第二个版本( for循环)之间存在主要差异。

  1. while() doesn't have any it++ for increasing iterator while()没有任何it++用于增加迭代器
  2. In while() you call only setX() while()您仅调用setX()

--> what would an be alternate way to store all of the nodes in the NodeManager class without having to name them? ->在无需命名节点的情况下将所有节点存储在NodeManager类中的另一种替代方法是什么?

May be you are looking for, 可能是您在寻找,

  1. std::vector (or equivalents), if you want simply an array std::vector (或等效项),如果只需要一个数组
  2. std::set , if you want to be able to find a node based on Node* std::set ,如果您希望能够基于Node*查找节点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM