分配带有数组元素的列表| C ++ STL
给定一个数组,我们必须创建一个列表,该列表应使用C++(STL)程序分配给该数组的所有元素。
示例
在这里,我们声明一个列表list1和一个数组arr,arr有5个元素,使用以下语句将arr的所有元素都分配给列表list1,
list1.assign(arr+0, arr+5);
这里,
list1是整数类型的列表
arr是一个整数数组
arr+0指向数组的第一个元素
而且,arr+4指向数组的最后一个元素
程序:
#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;
//数组声明
int arr[]={10, 20, 30, 40, 50};
//显示列表1-
cout<<"Before assign... "<<endl;
cout<<"Size of list1: "<<list1.size()<<endl;
cout<<"Elements of list1: ";
dispList(list1);
//将数组元素分配给列表
list1.assign(arr+0, arr+5);
//显示列表1-
cout<<"After assigning... "<<endl;
cout<<"Size of list1: "<<list1.size()<<endl;
cout<<"Elements of list1: ";
dispList(list1);
return 0;
}输出结果
Before assign... Size of list1: 0 Elements of list1: After assigning... Size of list1: 5 Elements of list1: 10 20 30 40 50