vector容器的插入和刪除(5)


功能描述:

  • 對vector容器進行插入、刪除操作

函數原型:

push_back(ele);   //尾部插入元素ele

pop_back();   //刪除最后一個元素

insert(const_iterator pos, ele);   //迭代器指向位置pos插入元素ele

insert(const_iterator pos, int count,ele);  //迭代器指向位置pos插入count個元素ele

erase(const_iterator pos);   //刪除迭代器指向的元素

erase(const_iterator start, const_iterator end);  //刪除迭代器從start到end之間的元素

clear();   //刪除容器中所有元素

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 void printVector(vector<int> &v)
 6 {
 7     for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
 8     {
 9         cout << *it << " ";
10     }
11     cout << endl;
12 }
13 
14 
15 void test_01()
16 {
17     vector<int> v1;
18     //尾插
19     v1.push_back(10);
20     v1.push_back(20);
21     v1.push_back(30);
22     v1.push_back(40);
23     v1.push_back(50);
24     printVector(v1);
25 
26     //尾刪
27     v1.pop_back();
28     printVector(v1);
29 
30     //插入
31     v1.insert(v1.begin(), 100);
32     printVector(v1);
33 
34     v1.insert(v1.begin(), 2, 1000);
35     printVector(v1);
36 
37     //刪除
38     v1.erase(v1.begin());
39     printVector(v1);
40 
41     v1.erase(v1.begin(), v1.end());
42     printVector(v1);
43 
44     //清空
45     v1.clear();
46     printVector(v1);
47 
48 }
49 
50 int main(void)
51 {
52     test_01();
53 
54     system("pause");
55     return 0;
56 
57 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM