Vector使用中的注意点

Vector的删除方法使用中存在以下注意点: 
1、尽量不要使用remove方法,因为这是在list接口中提供的方法 
2、尽量使用removeelementAt方法,这是正规的vector的方法 

以下代码看似没有问题,其实问题非常的大,出错时可以使整个线程挂起! 

 

vectorlength = myvector.size();
for(int i=0; i < vectorlength; i++)
{
    myvector.removeElementAt(i);
}

 

 

这样的代码运行过程中可能会出现arrayindexoutofbound的出错 
这是因为: 
removeElementAt方法每次执行完毕后会将vector的size减1 
而这个方法每次执行的时候都会检查参数index和vector的size的大小关系,如果index >= size,就会出现以上的错误 

所以,上述代码中,当删到index >= size时就会出错 

 

BTW: C++ stl vector也是如此。 

posted @ 2011-01-03 12:50  super119  阅读(255)  评论(0编辑  收藏  举报