STL——容器(deque)deque 的插入 insert()


deque.insert(pos,elem);

//在pos位置插入一個elem元素的拷貝,返回新數據的位置。

 1 #include <iostream>
 2 #include <deque>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     deque<int> deqInt_A, deqInt_B;
 9 
10     deqInt_A.push_back(1);
11     deqInt_A.push_back(2);
12     deqInt_A.push_back(3);
13 
14     cout << "遍歷deqInt_A" << endl;
15     for (deque<int>::iterator it = deqInt_A.begin(); it != deqInt_A.end(); it++)
16     {
17         cout << *it << " ";
18     }
19 
20     //在首位置插入1個數
21     deqInt_A.insert(deqInt_A.begin(), 0);
22 
23     cout << "\ninsert 插入后,遍歷deqInt_A" << endl;
24     for (deque<int>::iterator it = deqInt_A.begin(); it!= deqInt_A.end(); it++)
25     {
26         cout << *it << " ";
27     }
28     
29     return 0;
30 }

打印結果:

 

 

deque.insert(pos,n,elem);

//在pos位置插入n個elem數據,無返回值。

 1 #include <iostream>
 2 #include <deque>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     deque<int> deqInt_A, deqInt_B;
 9 
10     deqInt_A.push_back(1);
11     deqInt_A.push_back(2);
12     deqInt_A.push_back(3);
13 
14     cout << "遍歷deqInt_A" << endl;
15     for (deque<int>::iterator it = deqInt_A.begin(); it != deqInt_A.end(); it++)
16     {
17         cout << *it << " ";
18     }
19 
20     //在首位置+1處 插入2個0
21     deqInt_A.insert(deqInt_A.begin() + 1, 2, 0);
22 
23     cout << "\ninsert 插入后,遍歷deqInt_A" << endl;
24     for (deque<int>::iterator it = deqInt_A.begin(); it!= deqInt_A.end(); it++)
25     {
26         cout << *it << " ";
27     }
28     
29     return 0;
30 }

打印結果:

 

 

deque.insert(pos,beg,end);

//在pos位置插入[beg,end)區間的數據,無返回值

 1 #include <iostream>
 2 #include <deque>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     deque<int> deqInt_A, deqInt_B;
 9 
10     deqInt_A.push_back(1);
11     deqInt_A.push_back(2);
12     deqInt_A.push_back(3);
13 
14     deqInt_B.push_back(10);
15     deqInt_B.push_back(20);
16     deqInt_B.push_back(30);
17 
18     cout << "遍歷deqInt_A" << endl;
19     for (deque<int>::iterator it = deqInt_A.begin(); it != deqInt_A.end(); it++)
20     {
21         cout << *it << " ";
22     }
23     cout << "\n遍歷deqInt_B" << endl;
24     for (deque<int>::iterator it = deqInt_B.begin(); it != deqInt_B.end(); it++)
25     {
26         cout << *it << " ";
27     }
28 
29     //在首位置+1處 插入deqInt_B
30     deqInt_A.insert(deqInt_A.begin() + 1, deqInt_B.begin(), deqInt_B.end());
31     cout << "\n在首位置+1處 插入deqInt_B" << endl;
32     for (deque<int>::iterator it = deqInt_A.begin(); it!= deqInt_A.end(); it++)
33     {
34         cout << *it << " ";
35     }
36     
37     return 0;
38 }

打印結果:

 

 

 

 

 

 

===================================================================================================================

 


免責聲明!

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



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