简体   繁体   English

调试断言失败-向量迭代器不兼容

[英]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.

相关问题 std::vector 断言失败(向量迭代器不兼容) - std::vector Assertion failed (vector iterators incompatible) 调试断言:向量迭代器不兼容(C ++) - Debug Assertion : Vector iterators incompatible (C++) 调试断言失败! 表达式列表迭代器不兼容 - debug assertion failed! expression list iterators incompatible 调试断言失败 - 数组迭代器不兼容 - Debug Assertion Failed - Array Iterators Incompatible 在C ++中,会弹出“调试断言失败”窗口,并且我得到矢量迭代器不兼容的错误运行时 - In C++, Debug assertion failed window pops up & I get vector iterators incompatible error runtime 向量迭代器不兼容:DEBUG - Vector iterators incompatible: DEBUG C++ 调试断言失败; 表达式:列表迭代器不兼容 - C++ Debug Assertion Failed; Expression: list iterators incompatible 调试断言失败:迭代器无效 - Debug assertion failed: invalid iterators 调试断言错误 - 列表迭代器不兼容 - Debug assertion error - List iterators incompatible C ++迭代器作为lambda函数中的参数,断言失败:“向量迭代器不兼容” - C++ iterator as argument in lambda function, assertion failed: “vector iterators incompatible”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM