std::remove

C++ VRCTOR中实际删除元素使用的是容器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 }
 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 }
container.erase(remove_if(container.begin(), container.end(), pred), container.end()); 

文章链接: https://www.mfisp.com/21655.html

文章标题:std::remove

文章版权:梦飞科技所发布的内容,部分为原创文章,转载请注明来源,网络转载文章如有侵权请联系我们!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
建站教程

【C++】代码实现:运用 std::list 的 remove_if() 函数剔除数组中超出上下限的数据

2023-6-29 12:55:50

建站教程

C++设计模式:过滤器模式

2023-6-29 13:22:07

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
客户经理
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索

梦飞科技 - 最新云主机促销服务器租用优惠