简体   繁体   English

我如何错误地使用向量迭代器?

[英]How am I using vector iterators incorrectly?

This code works: 此代码有效:

for (unsigned int i = 0; i != m_cResources.getLoadedPlayers().size(); i++) {
    m_cResources.getLoadedPlayers()[i]->update();
}

When I try to use iterators with the following code, my programs hangs and stops working: 当我尝试将迭代器与以下代码一起使用时,我的程序挂起并停止工作:

for (std::vector<CPlayer*>::iterator i = m_cResources.getLoadedPlayers().begin();
        i != m_cResources.getLoadedPlayers().end(); i++) {
    (*i)->update();
}

getLoadedPlayers() returns the vector of CPlayer*. getLoadedPlayers()返回CPlayer *的向量。 Update is a member function in CPlayer. 更新是CPlayer中的成员函数。

I've never used iterators before so I'm not really sure what is wrong. 我以前从未使用过迭代器,所以我不确定什么地方出了错。 I don't think the error is outside of this code because the first block works. 我不认为该错误不在此代码之外,因为第一个块有效。 So I assume my implementation of the iterator is wrong. 所以我认为我的迭代器实现是错误的。 Any ideas? 有任何想法吗?

EDIT: getLoadedPlayers() returns the vector by value, not reference. 编辑:getLoadedPlayers()返回值的向量,而不是引用。 Would this most likely be the problem? 这很可能是问题所在吗? But then wouldn't the first code block also not work? 但是,第一个代码块也不会起作用吗? I will test this as soon as I can. 我将尽快对此进行测试。

The update function modifies member values in a CPlayer based on flags previously set. 更新功能根据先前设置的标志修改CPlayer中的成员值。

Why not use C++'s for each? 为什么不为每个使用C ++?

for (auto &i : m_cResources.getLoadedPlayers()) {
  i->update();
}

If as you said getLoadedPlayers() returns the vector by value, not reference then the first loop also has no sense because in each iteration a new copy of the vector is used in expression 如果如您所说,getLoadedPlayers()按值返回向量,而不是按引用返回向量,则第一个循环也没有意义,因为在每次迭代中,都会在表达式中使用向量的新副本

m_cResources.getLoadedPlayers()[i]->update();

When you use iterators in the loop 在循环中使用迭代器时

for (std::vector<CPlayer*>::iterator i = m_cResources.getLoadedPlayers().begin();
        i != .getLoadedPlayerm_cResourcess().end(); i++) 

then iterator i and getLoadedPlayerm_cResourcess().end() point to differenent memory extent. 然后迭代器i和getLoadedPlayerm_cResourcess()。end()指向不同的内存范围。 So they may not be compared. 因此它们可能无法比较。

If you want that your loops had any sense you should use reference to the original vector. 如果您希望循环有任何意义,则应使用对原始向量的引用。

Your vector is returned by value, so your iterator which is incremented each iteration of the loop will never "meet" the end iterator in the loop exit condition : it belongs to another vector (changed at each iteration). 向量是按值返回的,因此在循环的每次迭代中递增的迭代器永远不会在循环退出条件下“满足”最终迭代器:它属于另一个向量(每次迭代都更改)。 So your code invokes undefined behavior by dereferencing an invalid iterator (and the underlying pointer) 因此,您的代码通过取消引用无效的迭代器(和基础指针)来调用未定义的行为

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

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