Fork me on GitHub

STL——容器(List)List 的构造函数

list<T> lstT —— list 对象的默认构造

list 与 vector 一样,同样采用模板类实现,对象的默认构造形式:list<T> lstT  如:

 1 #include <iostream>
 2 #include <list>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     list<int> listInt;                    //定义一个存放 int 的 list 容器
 9     cout << "listInt size:" << listInt.size() << endl;
10     list<float> listFloat;                //定义一个存放 float 的 list 容器
11     cout << "listInt size:" << listFloat.size() << endl;
12     list<string> listString;             //定义一个存放 string 的 list 容器
13     cout << "listInt size:" << listString.size() << endl;
14 
15     return 0;
16 }

打印结果:

 

 

 

list(beg, end) —— list 对象的带参构造&拷贝构造

构造函数将(beg, end)区间中的元素拷贝给本身,如以下三种方法:

 1 #include <iostream>
 2 #include <list>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     list<int> listInt;                    //定义一个存放 int 的 list 容器
 9     listInt.push_back(1);
10     listInt.push_back(2);
11     listInt.push_back(3);
12     int num[] = { 111,222,333 };
13 
14     //方法一    将 (beg, end)区间中的元素拷贝给本身
15     list<int> listInt_A(listInt.begin(), listInt.end());        //1 2 3
16     for (list<int>::iterator it = listInt_A.begin(); it != listInt_A.end(); it++)
17     {
18         cout << *it << " ";
19     }
20     cout << endl;
21 
22     //方法一(变种)    将一个数组中的元素拷贝给本身
23     list<int> listInt_B(num, num + size(num));                //111 222 333
24     for (list<int>::iterator it = listInt_B.begin(); it != listInt_B.end(); it++)
25     {
26         cout << *it << " ";
27     }
28     cout << endl;
29 
30     //方法二    list(n, elem)    构造函数将 N 个 elem 拷贝给本身
31     list<int> listInt_C(3, 888);                                //888 888 888
32     for (list<int>::iterator it = listInt_C.begin(); it != listInt_C.end(); it++)
33     {
34         cout << *it << " ";
35     }
36     cout << endl;
37 
38     //方法三    list(const list & lst)    拷贝构造函数
39     list<int> listInt_D(listInt_A);                                //1 2 3
40     for (list<int>::iterator it = listInt_D.begin(); it != listInt_D.end(); it++)
41     {
42         cout << *it << " ";
43     }
44 
45     return 0;
46 }

 

打印结果:

 

 

 

 

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

posted @ 2020-05-04 19:51  索智源  阅读(772)  评论(0编辑  收藏  举报