它将元素分配或替换到列表中。
示例
在给定的示例中,有3种不同的方法用于为列表分配/替换元素。
#include <iostream>
#include <list>
using namespace std;
//显示列表的功能
void dispList(list<int> L)
{
//在列表中声明Interator-
list<int>::iterator l_iter;
for (l_iter = L.begin(); l_iter != L.end(); l_iter++)
cout<< *l_iter<< " ";
cout<<endl;
}
int main(){
list<int> list1;
list<int> list2;
list<int> list3;
list<int> list4;
//将100分配给5个元素
list1.assign(5,100);
cout<<"size of list1: "<<list1.size()<<endl;
cout<<"Elements of list1: ";
dispList(list1);
//将list1的所有元素分配给list2-
list2.assign(list1.begin(), list1.end());
cout<<"size of list2: "<<list2.size()<<endl;
cout<<"Elements of list2: ";
dispList(list2);
//通过数组元素分配列表
int arr []={10, 20, 30, 40};
list3.assign(arr, arr+4);
cout<<"size of list3: "<<list3.size()<<endl;
cout<<"Elements of list3: ";
dispList(list3);
return 0;
}输出结果
size of list1: 5 Elements of list1: 100 100 100 100 100 size of list2: 5 Elements of list2: 100 100 100 100 100 size of list3: 4 Elements of list3: 10 20 30 40
参考:list::assign()