我迷路了:除非函数调用(Z_UB-> set())在++之前,std :: string向量的迭代器才能完美工作。下面的代码:C++迭代器随机失效
std::vector<std::string>::iterator it = g_SPP.scenarios->getVector().begin();
std::cout << "begin of vector: " << *it << std::endl;
Z_UB->set("s1", "scn2", 350);
it++;
std::cout << "second of vector: " << *it << std::endl;
创建以下输出
begin of vector: scn1
但是,如果我将函数调用是这样的:
std::vector<std::string>::iterator it = g_SPP.scenarios->getVector().begin();
std::cout << "begin of vector: " << *it << std::endl;
it++;
std::cout << "second of vector: " << *it << std::endl;
Z_UB->set("s1", "scn2", 350);
结果如下,这是预期行为:
begin of vector: scn1
second of vector: scn2
里面的Z_UB-> set()函数没有什么离开,但调用本身:
void Parameter::set(std::string _i, std::string _j, float value) {
//int i = indexSets[0]->backIndex(_i);
//int j = indexSets[1]->backIndex(_j);
//data2D[0][0] = value;
}
所以,如果我叫Z_UB->设置()函数,我创建迭代器后,访问它会使程序崩溃。我错过了关于迭代器的事情吗?
这里没有足够的信息来诊断您的具体问题。迭代器不会“随机地”失效,所以问题出现在你的代码中,但是在你的代码中这个帖子里并不清楚问题所在。 'Z_UB'确实是'Parameter'类型的吗?还有其他什么类型的,可以修改底层'vector'的东西吗?在向量的内部存储器的大小调整过程中,矢量迭代器无效。 – Chad
getVector()是否返回对矢量或副本的引用? –
它返回的矢量副本(根据我没有使用&任何地方) – buhmann