[英]Debug assertion failed - vector iterators are incompatible
I'm trying to compare two iterators from the same vector, but for some reason it threw me this error: 我试图比较同一个向量中的两个迭代器,但是由于某种原因,它使我犯了这个错误:
That is the relevant code function: 那是相关的代码功能:
function, which finds the first iterator and returns a copy of it: 函数,它找到第一个迭代器并返回它的副本:
static const vector<Player*>::const_iterator findPlayer(
const vector<Player*> players, int id)
{ ///const
vector<Player*>::const_iterator found
= find_if(begin(players), end(players), [id] (Player* player) {
return player->getId() == id;
});
return found;
}
Those are the comparation strokes of code: 这些是代码的比较笔画:
vector<Player*>::const_iterator found = findPlayer(this->_players_in, *cur_id);
if(found != end(this->_players_in))
Does somebody know the reason for that? 有人知道原因吗?
It looks like you're making a copy of the vector, using find_if to get an iterator into that copy, and returning that iterator. 看起来您正在复制向量,使用find_if将迭代器添加到该副本中,然后返回该迭代器。 This is bad because the vector that iterator points into will be destroyed when you return.
这很不好,因为当您返回时,迭代器指向的向量将被破坏。
You should pass players by reference instead. 您应该通过参考传递球员。 Your declaration should look like:
您的声明应如下所示:
static const vector<player*>::const_iterator findPlayer(const vector<Player*>& players, int id)
(note the & ) (请注意&)
This ensures that the iterator you return is pointing to the same container that the caller provided. 这样可以确保您返回的迭代器指向调用方提供的相同容器。
Note: this kind of assertion is not standard. 注意:这种断言不是标准的。 It's quite kind of your compiler/environment to provide it for debug builds.
您的编译器/环境非常适合提供调试版本。 I implemented these kinds of checks on some iterators for a custom container and it saved me on least a dozen occasions.
我在自定义容器的某些迭代器上实施了此类检查,这至少使我节省了十几次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.