ca13a_c++_顺序容器的操作6删除元素

/*ca13a_c++_顺序容器的操作6删除元素
c.erase(p) //删除迭代器p指向的位置
c.erase(b,e) //删除b to e之间的数据,迭代器b包括,e不包括
c.clear()//删除所有
c.pop_back() //删除最后一个
c.pop_front() //删除最前的一个
find查找算法
list<string>::iterator iter1= find(slist.begin(), slist.end(), s);
注意:c.pop_front()只适用于list和deque容器
vector没有pop_front.
txwtech

 1 /*ca13a_c++_顺序容器的的操作6删除元素
 2 c.erase(p)  //删除迭代器p指向的位置
 3 c.erase(b,e) //删除b to e之间的数据,迭代器b包括,e不包括
 4 c.clear()//删除所有
 5 c.pop_back() //删除最后一个
 6 c.pop_front() //删除最前的一个
 7 find查找算法
 8 list<string>::iterator iter1= find(slist.begin(), slist.end(), s);
 9 注意:c.pop_front()只适用于list和deque容器
10 vector没有pop_front.
11 txwtech
12 */
13 #include <iostream>
14 #include <list>
15 #include <deque>
16 #include <vector>
17 #include <string>
18 #include <algorithm>
19 
20 using namespace std;
21 
22 int main()
23 {
24     list<string> slist;
25     slist.push_back("apple");
26     slist.push_back("bill");
27     slist.push_back("cat");
28     slist.push_back("dog");
29     slist.push_back("egg");
30     slist.push_back("fish");
31     slist.push_back("girl");
32 
33     slist.pop_front();
34     slist.pop_back();
35 
36     string s("dog");//s="dog"
37     string s2("fish");
38     list<string>::iterator iter1= find(slist.begin(), slist.end(), s);
39     list<string>::iterator iter2 = find(slist.begin(), slist.end(), s2);
40 
41     if (iter1 != slist.end() && iter2 != slist.end())
42         //slist.erase(iter1);//删除查找到的内容
43     {
44         slist.erase(iter1, iter2);//删除iter1 到iter2,不包括iter2
45         cout << "找到了dog与fish,dog删除掉了,不包括fish" << endl;
46     }
47 
48     else
49         cout << "没有找到" << endl;
50 
51     slist.clear();//清空数据
52     if (!slist.empty())//如果非空,就显示
53     {
54         for (list<string>::iterator iter = slist.begin();
55             iter != slist.end(); ++iter)
56             cout << *iter << endl;
57     }
58     else
59         cout << "目前容器是空的。" << endl;
60 
61     
62     return 0;
63 }

 

posted @ 2020-02-15 21:42  txwtech  阅读(165)  评论(0编辑  收藏  举报