简体   繁体   English

C ++列表迭代器不兼容

[英]C++ List Iterators Incompatible

This is the code that I have in my main.cpp 这是我main.cpp中的代码

std::list<AbstractBlock*>::iterator i;

    for (i = universe.getLoadedBlocks().begin(); i != universe.getLoadedBlocks().end(); i++){
        window.draw((*i)->draw());

    }

Universe.cpp: Universe.cpp:

std::list<AbstractBlock*> Universe::getLoadedBlocks(){
    return chunkManager->getLoadedBlocks();
}

CunkManager.cpp: CunkManager.cpp:

std::list<AbstractBlock*> ChunkManager::getLoadedBlocks(){
    return loadedBlocks;
}

And loadedBlocks is an std::list<AbstractBlock*> 并且loadingBlocks是std::list<AbstractBlock*>

I'm experimenting with lists and trying them out for the first time... I'm not sure why I'm getting this error 我正在尝试使用列表,并首次尝试使用它们...我不确定为什么会出现此错误

std::list<AbstractBlock*> Universe::getLoadedBlocks() { ... }
^^^^^^^^^^^^^^^^^^^^^^^^^ // This returns a copy of the list

Therefore, universe.getLoadedBlocks().begin() uses one copy of the list and universe.getLoadedBlocks().end() uses a different copy of the list. 因此, universe.getLoadedBlocks().begin()使用列表的一个副本,而universe.getLoadedBlocks().end()使用列表的另一个副本。 This is why the iterators are incompatible (ie, they are from different lists). 这就是迭代器不兼容的原因(即,它们来自不同的列表)。

Said another way, the begin iterator of one list instance will never be equal to the end iterator from a different list instance. 换句话说,一个列表实例的begin迭代器永远不会等于其他列表实例的end迭代器。

If you don't change the getLoadedBlocks() function you could try: 如果不更改getLoadedBlocks()函数,则可以尝试:

std::list<AbstractBlock*> values = universe.getLoadedBlocks();
for (i = values.begin(); i != values.end(); i++) // Note: You should use ++i here (for possible efficiency benefits)
{
    window.draw((*i)->draw());
}

Edit 编辑

As Jarod42 points out you could also use the more convenient/succinct range-based for loop, assuming you're using a C++11 compatible compiler. 正如Jarod42所指出的,假设您使用的是与C ++ 11兼容的编译器,那么您还可以使用更方便/更简洁的基于范围的for循环。

for (auto& block : universe.getLoadedBlocks())
{
    window.draw(block->draw());
}

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

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