可能重複:
Erasing from a std::vector while doing a for each?刪除元素,而迭代同一矢量
我試圖實現頂點根據這個算法着色;
/*
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
*/
我不明白「add v to currentColor」。但我認爲,這意味着將currentColor分配給v。因此,什麼是「set」?無論如何,問題是在迭代它時刪除向量中的元素。這是代碼。
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;
}
我覺得it2 = uc.erase(it2);
線已經普遍使用,但它提供了運行時錯誤。
你能告訴我們什麼錯誤? – vidit 2012-03-29 14:19:52