gpt4 book ai didi

c++ - std::vector 迭代器不兼容

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:47 25 4
gpt4 key购买 nike

在我不理解的 C++ 程序执行过程中出现错误( vector 迭代器不兼容)。 [(Windows/Visual C++ 2008 Express)]

这是我的问题的简化版本:

#include <vector>

class A
{
int mySuperInt;
public:
A(int val) : mySuperInt(val) {}
};
class B
{
std::vector<A*> myAs;
public:
B()
{
myAs.push_back(new A(1));
};
const std::vector<A*> getA() const {return myAs;}
};

int main()
{
std::vector<B>* myBs = new std::vector<B>;

myBs->push_back(B());

std::vector<B>::const_iterator it_B = myBs->begin();
for ( ; it_B != myBs->end(); ++it_B)
{
std::vector<A*>::const_iterator it_A = it_B->getA().begin();
for ( ; it_A != it_B->getA().end(); ++it_A) // <-- Error during execution: vector iterator incompatibles
{
// Do stuff
// ...
}
}
}

我错过了什么吗?

预先感谢您的回答。

最佳答案

您的 getA() 函数按值返回一个 vector 。您正在将循环迭代器初始化到该 vector 的开头,但由于返回的 vector 是临时的,因此它会在该行的末尾被销毁。

// at the end of this line the vector returned by getA is gone, so it_A is invalid.
std::vector<A*>::const_iterator it_A = it_B->getA().begin();

因此迭代器不再有效。您应该像这样返回对 vector 的引用(注意 &):

const std::vector<A*> & getA() const {return myAs;}

关于c++ - std::vector 迭代器不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3993811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com