通过分配另一个列表的所有元素来创建列表| C ++ STL
有两种方法可以实现它...
1)通过直接将现有列表分配给新列表
list<int> list2 = list1;
2)通过使用list::assign()函数
list<int> list2;
list2.assign(list1.begin(), list1.end());示例
在此示例中,我们有一个包含10个元素的列表list1,并且正在创建另一个列表list2,将使用list:assign()函数(即“listheader”的库函数)通过list1分配list2的元素。并且,我们还创建了一个列表list3,该列表将直接通过list1进行分配。
程序:
#include <iostream>
#include <list>
using namespace std;
//显示列表的功能
void dispList(list<int> L)
{
//在列表中声明迭代器
list<int>::iterator l_iter;
for (l_iter = L.begin(); l_iter != L.end(); l_iter++)
cout<< *l_iter<< " ";
cout<<endl;
}
int main(){
//list1声明
list<int> list1 = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
//显示列表1-
cout<<"Size of list1: "<<list1.size()<<endl;
cout<<"Elements of list1: ";
dispList(list1);
//声明list2并分配元素
//列表1-
list<int> list2;
list2.assign(list1.begin(), list1.end());
//显示列表2-
cout<<"Size of list2: "<<list2.size()<<endl;
cout<<"Elements of list2: ";
dispList(list2);
//声明list3
list<int> list3 = list1;
//显示列表3-
cout<<"Size of list3: "<<list3.size()<<endl;
cout<<"Elements of list3: ";
dispList(list3);
return 0;
}输出结果
Size of list1: 10 Elements of list1: 10 20 30 40 50 60 70 80 90 100 Size of list2: 10 Elements of list2: 10 20 30 40 50 60 70 80 90 100 Size of list3: 10 Elements of list3: 10 20 30 40 50 60 70 80 90 100