C++ 迭代同一向量时擦除向量中的元素
可能重复:C++ 迭代同一向量时擦除向量中的元素,c++,vector,C++,Vector,可能重复: 我试图根据这个算法实现垂直着色 /* Given G=(V,E): Compute Degree(v) for all v in V. Set uncolored = V sorted in decreasing order of Degree(v). set currentColor = 0. while there are uncolored nodes: set A=first element of uncolored remove A from uncolore
我试图根据这个算法实现垂直着色
/*
Given G=(V,E):
Compute Degree(v) for all v in V.
Set uncolored = V sorted in decreasing order of Degree(v).
set currentColor = 0.
while there are uncolored nodes:
set A=first element of uncolored
remove A from uncolored
set Color(A) = currentColor
set coloredWithCurrent = {A}
for each v in uncolored:
if v is not adjacent to anything in coloredWithCurrent:
set Color(v)=currentColor.
add v to currentColor.
remove v from uncolored.
end if
end for
currentColor = currentColor + 1.
end while
*/
我不懂“将v添加到currentColor”这行,但我想,这意味着将currentColor分配到v。因此,“集合”是什么?无论如何,问题是在迭代向量时擦除向量中的元素。这是代码
vector<struct Uncolored> uc;
vector<struct Colored> c;
int currentColor = 0;
struct Colored A;
struct Colored B;
vector<struct Uncolored>::iterator it;
vector<struct Uncolored>::iterator it2;
vector<struct Colored>::iterator it3;
for(it=uc.begin();it<uc.end();it++){
A.id = (*it).id;
uc.erase(uc.begin());
A.color = currentColor;
c.push_back(A);
for(it2=uc.begin();it2<uc.end();it2++) {
it3=c.begin();
while(it3 != c.end()) {
if( adjacencyMatris[(*it2).id][(*it3).id] == 0 ) {
B.id = (*it2).id;
it2 = uc.erase(it2);
B.color = currentColor;
c.push_back(B);
}
it3++;
}
}
currentColor = currentColor + 1;
}
向量uc;
载体c;
int currentColor=0;
结构着色A;
结构色B;
向量::迭代器;
向量::迭代器it2;
向量::迭代器it3;
对于(it=uc.begin();它可以指向向量
这将使所有迭代器和对position(或first)及其后续元素的引用无效
您需要将erase
的结果添加到迭代器中(它将指向删除的元素之后的元素),然后使用它
for(it=uc.begin();it<uc.end();++it){
A.id = (*it).id;
uc.erase(uc.begin());
...
}
for(it=uc.begin();行中的it:
it2 = uc.erase(it2);
迭代器it2
指向的元素从向量中移除,元素在内存中移动以填补使it2
无效的间隙it2
获得一个新值,现在指向移除的元素后的第一个元素或向量的结尾(如果移除的元素是最后一个)。这意味着在删除元素后,您不应推进it2
。建议的remove-erase-idiom
的替代方法是一个简单的技巧:
for(it2 = uc.begin(); it2 != uc.end();)
{
...
if(...)
{
it2 = uc.erase(it2);
}
else
{
++it2;
}
...
}
你可以阅读更多关于这方面的内容
编辑:
关于您的评论,您可以使用一个标志来传递元素是否已被擦除的信息,并且您可以在退出内部循环时检查该信息:
for(it2=uc.begin(); it2 != uc.end();)
{
bool bErased = false;
for(it3 = c.begin(); it3 != c.end(); ++it3)
{
if(adjacencyMatris[(*it2).id][(*it3).id] == 0 )
{
B.id = (*it2).id;
it2 = uc.erase(it2);
bErased = true;
B.color = currentColor;
c.push_back(B);
break;
}
}
if(!bErased)
++it2;
}
从uc
中删除一个元素后,您需要从内部循环中断。在外部循环的下一次迭代中,您可以通过有效的迭代器访问uc
中的下一个元素。如果需要ite,请将索引存储到向量中,而不是使用迭代器
类型rator——可能用于传递到erase
——您可以说begin()+myIndex
来生成迭代器
这也使循环看起来更熟悉,例如
for(ind=0; ind < uc.size(); ind++) {
for(ind=0;ind
出现运行时错误是因为it2=uc.erase(it2);
返回最后删除的元素后面的迭代器,因此it2++
中的for(it2=uc.begin();it2如果迭代器不在末尾,我必须继续迭代。事实上,中断;
退出while,但不退出for。这样,for循环使it2++并与下一个迭代器迭代。在我的代码中,erase和++it2不在同一个循环中scope@miqbal我编辑了我的答案来解决这个问题。
if( adjacencyMatris[(*it2).id][(*it3).id] == 0 ) {
B.id = (*it2).id;
uc.erase(it2);
B.color = currentColor;
c.push_back(B);
break;
}