C++ 卡住矢量迭代器不兼容,找不到原因

C++ Stuck with vector iterators incompatible, can't find why

本文关键字:找不到 不兼容 迭代器 C++      更新时间:2023-10-16

每当我尝试通过std::vector进行交互时,它会一直告诉我:vector迭代器不兼容

这是导致我崩溃的函数:

// These 2 typedefs are declared in structs.h
typedef std::pair<uint32_t, Object*> PlayerContainerPair;
typedef std::vector<PlayerContainerPair> PlayerContainers;
// This is a variable from Player class in player.h
PlayerContainers m_containers;
// Definition of the function found in player.cpp
int32_t Player::GetContainerId(Object* container)
{
    for (PlayerContainers::const_iterator cl = m_containers.begin(); cl != m_containers.end(); ++cl){
        if (cl->second == container)
            return static_cast<int32_t>(cl->first);
    }
    return -1;
}

基本上每当我尝试通过向量循环时,它会一直崩溃我的应用程序,我检查了对象,它是一个对象类,它不是空的。

还有什么原因导致这个错误?

using

for (auto cl = m_containers.begin(); cl != m_containers.end(); ++cl){
    if (cl->second == container)
        return static_cast<int32_t>(cl->first);
}

应该能解决你的问题

删除&如下所示

一个最小的例子

#include <iostream>
#include <string>
#include <tuple>
#include <cstdint>
#include <vector>
struct Object {};
// These 2 typedefs are declared in structs.h
typedef std::pair<uint32_t, Object*> PlayerContainerPair;
typedef std::vector<PlayerContainerPair> PlayerContainers;
// This is a variable from Player class in player.h
PlayerContainers m_containers;
// Definition of the function found in player.cpp
int32_t GetContainerId(Object* container)
{
    for (auto cl = m_containers.begin(); cl != m_containers.end(); ++cl){
        if (cl->second == container)
            return static_cast<int32_t>(cl->first);
    }
    return -1;
}
int main()
{
    Object* o = new Object;
    m_containers.push_back(PlayerContainerPair(1, o));
    std::cout << GetContainerId(o);
    return 0;
}

在vs2013

下按预期编译和运行