问题描述
我无法解除我在感恩节工作的问题,但是我被困在
应该很简单的事情上。我有一个具有二十四个
元素的向量。我需要删除位置相等的四个元素
零。下面的代码只删除了四个中的两个。有什么想法吗?
logfile<< " \\\
\\\
\\\
。 。 .removing flat positions" ;;
logfile<< vector size = << componentPerformance.size()<< endl;
int position = 0;
for(vector< cPerformance> :: iterator itr =
componentPerformance.begin(); itr! = componentPerform ance.end(); ++ itr)
{
position = itr-> returnPosition(); // returnPosition()返回一个浮点数
logfile<< endl<< itr-> returnSymbol()<< "位置= QUOT; <<
itr-> returnPosition();
if(position == 0)
{
logfile<< " \tremoving。 。 。 " << itr-> returnSymbol();
componentPerformance.erase(itr);
}
}
logfile.close();
I cannot relieve that I am working on Thanksgiving, but I am stuck over
something that should be simple. I have a vector that has twenty-four
elements. I need to remove the four elements whose positions equal
zero. The code below only removes two of the four. Any ideas?
logfile << "\n\n\n. . .removing flat positions";
logfile << "vector size=" << componentPerformance.size() << endl;
int position=0;
for (vector<cPerformance>::iterator itr =
componentPerformance.begin();itr!=componentPerform ance.end(); ++itr)
{
position=itr->returnPosition(); //returnPosition() returns a float
logfile << endl << itr->returnSymbol() << "Position=" <<
itr->returnPosition();
if(position==0)
{
logfile << "\tremoving. . . " << itr->returnSymbol();
componentPerformance.erase(itr);
}
}
logfile.close();
推荐答案
经典错误:-)
当你擦除时元素,''itr'实际上已指向下一个元素
(从技术上讲,实际上它被标准AFAIK无效)。因此
++ itr在for结束时跳过被移除的元素旁边的元素。
Mirek
Classic error :-)
When you "erase" the element, ''itr'' in fact points already to next one
(technically, in fact it is invalidated by standard AFAIK). Therefore
++itr at the end of "for" skips the element next to the removed one.
Mirek
难怪C ++贫民窟之外没有人认为C ++是语言
适合做任何实际工作:)
No wonder nobody outside C++ ghetto considers C++ to be language
suitable to do any real work anymore :)
我相信这段代码是错误的 - 它会跳过已删除的元素。
I believe this code is wrong - it skips elements past removed one.
这篇关于从向量中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!