std::remove

C++ vector 删除符合条件的元素

C++ vector中实际删除元素使用的是容器vecrot中std::vector::erase()方法。

C++ 中std::remove()并不删除元素,因为容器的size()没有变化,只是元素的替换。

1.std::vector::erase()

  函数原型:iterator erase (iterator position);  //删除指定元素

       iterator erase (iterator first, iterator last);  //删除指定范围内的元素

  返回值:指向删除元素(或范围)的下一个元素。(An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.)

2.代码实例

复制代码

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 using namespace std;
 5 
 6 int out(vector<int> &iVec)
 7 {
 8     for(int i=0;i<iVec.size();i++)
 9         cout<<iVec[i]<<ends;
10     cout<<endl;
11     return 0;
12 }
13 
14 int main()
15 {
16     vector<int> iVec;
17     vector<int>::iterator it;
18     int i;
19     for( i=0;i<10;i++)
20         iVec.push_back(i);
21 
22     cout<<"The Num(old):";out(iVec);
23     for(it=iVec.begin();it!=iVec.end();)
24     {
25         if(*it % 3 ==0)
26             it=iVec.erase(it);    //删除元素,返回值指向已删除元素的下一个位置    
27         else
28             ++it;    //指向下一个位置
29     }
30     cout<<"The Num(new):";out(iVec);
31     return 0;
32 }

复制代码

 执行输出:

 

 *********************************************************************************************************

remove_if详解,配合erase

 https://blog.csdn.net/u010913001/article/details/53348580

 #include <algorithm>
forward_iterator remove_if( forward_iterator start, forward_iterator end, Predicate p ); 
  • 1
  • 2

函数remove_if()移除序列[start, end)中所有应用于谓词p返回true的元素.
此函数返回一个指向被修剪的序列的最后一个元素迭代器.
记住, remove_if()并不会实际移除序列[start, end)中的元素; 如果在一个容器上应用remove_if(), 容器的长度并不会改变(remove_if()不可能仅通过迭代器改变容器的属性), 所有的元素都还在容器里面. 实际做法是, remove_if()将所有应该移除的元素都移动到了容器尾部并返回一个分界的迭代器. 移除的所有元素仍然可以通过返回的迭代器访问到. 为了实际移除元素, 你必须对容器自行调用erase()以擦除需要移除的元素. 这也是erase-remove idiom名称的由来:

container.erase(remove_if(container.begin(), container.end(), pred), container.end()); 
  • 1
vector<int> vt;
int arr[9] = {1,2,3,4,5,6,7,8,9};
vt.assign(arr,arr+9);
vector<int>::iterator pos;
pos = remove_if(vt.begin(),vt.end()),compose2(logical_and<bool>(),bind2nd(greater<int>(),4),bind2nd(less<int>(),7))); //删除比4大且比7小的数
vt.erase(pos,vt.end()); //全部移动到末尾了
//结果1,2,3,4,7,8,9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

remove_if()类似于partition(), 但有两点不同: 1) 它们使用的谓词条件刚好相反. 2) remove_if只强调前面部分(第二部分不再需要了)
remove_if()以线性时间(linear time)运行.
remove_if()不能用于关联容器如set<>或map<>.

猜你喜欢

转载自blog.csdn.net/brucethl/article/details/82900667
std
今日推荐