在vector中,怎樣刪除某個指定值的元素

【在vector中,怎樣刪除某個指定值的元素】
Vectors provide no operation to remove elements directly that have a certain value. You must use an algorithm to do this.
一.刪除所有滿足條件的元素
For example, the following statement removes all elements that have the value val:
   std::vector<Elem> coll;
   ...
   //remove all elements with value val
   coll.erase(remove(coll.begin(),coll.end(),
                     val),
              coll.end());
二.只刪除第一個
To remove only the first element that has a certain value, you must use the following statements:
   std::vector<Elem> coll;
   ...
   //remove first element with value val
   std::vector<Elem>::iterator pos;
   pos = find(coll.begin(),coll.end(),
              val);
   if (pos != coll.end()) {
       coll.erase(pos);
   }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章