一道到面试题引出iterator++的问题(程序宝典96-97)

以下是某软件公司的面试题:(以下代码有什么问题?如何修改?)
#include <vector>
#include <iterator>
using namespace std;

void printMy(vector<int>);

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> vecInt;
	vecInt.push_back (1);
	vecInt.push_back (6);
	vecInt.push_back (6);
	vecInt.push_back (3);

	vector<int>::iterator  itor;
	vector<int>::iterator  itor2;
        itor=vecInt.begin ();
	for(itor=vecInt.begin ();itor!=vecInt.end ();)
	{
		if(6==*itor)
		{
		        itor2=itor;
			vecInt.erase (itor2);
		}
itor++; } printMy(vecInt); return 0; } void printMy(vector<int> vec) { cout<<"\nvector size is:"<<vec.size ()<<endl; vector<int>::iterator p=vec.begin (); }
程序员面试宝典是这样解析的:这是迭代器的问题,只能删除第一个6,以后迭代器就失效了,不能删除以后的元素。itor2=itor;这句说明两个迭代器是一样的。vecInt.erase (itor2);等于vecInt.erase (itor);,这是指针已经指向下一个元素6了。itor++;又自增,指向下一个元素3,略过了第二个6.
书给出的修改方法是这样的:方法1——使用vector模版里面的remove函数进行修改。方法2——为了让其不略过第二个6,可以使itor--,回到原来的位置上。
我在vs2008中对其进行编译运行不能成功,使用书中给的第二种方法也运行不成功。
我的理解是:在vecInt.erase (itor2)时,itor2(itor)迭代器失效,他们指向的空间被erase了,从而使itor2(itor)指向未知的空间了。所以程序运行到itor++处崩溃。
个人尝试这样修改:(改for循环里的部分)
for(itor=vecInt.begin ();itor!=vecInt.end ();)
    {
        if(6==*itor)
        {
            vecInt.erase (itor++);
        }
         else
            itor++;
    }

这也不能通过,自己的理解是这样的:在两序列点中itor变化两次,第一次移除,第二次自加;所以错了( 标准规定,在两个序列点之间,一个对象所保存的值最多只能被修改一次)。itor++首先产生副本itor,然后自加,注意在使用副本时不能改变副本(只能使用),否则会出现上述问题。



  

posted @ 2012-08-18 23:55  Marinan  阅读(513)  评论(0编辑  收藏  举报