Home »
C++ STL
Assign a list with array elements | C++ STL
Here, we are going to learn how to assign a list with the elements of an array in C++ STL?
Submitted by IncludeHelp, on November 02, 2018
Problem statement
Given an array and we have to create a list, that should be assigned with all elements of the array using C++ (STL) program.
Approach
Here, we are declaring a list list1 and an array arr, arr has 5 elements, all elements of the arr are assigning to the list list1 by using following statements,
list1.assign(arr+0, arr+5);
Here,
- list1 is a list of integer type
- arr is an integer array
- arr+0 points the first element of the array
- And, arr+4 points the last element of the array
C++ program to assign a list with array elements
#include <iostream>
#include <list>
using namespace std;
// function to display the list
void dispList(list<int> L) {
// declaring iterator to the list
list<int>::iterator l_iter;
for (l_iter = L.begin(); l_iter != L.end(); l_iter++) cout << *l_iter << " ";
cout << endl;
}
int main() {
// list1 declaration
list<int> list1;
// array declaration
int arr[] = {10, 20, 30, 40, 50};
// displaying list1
cout << "Before assign... " << endl;
cout << "Size of list1: " << list1.size() << endl;
cout << "Elements of list1: ";
dispList(list1);
// assigning array Elements to the list
list1.assign(arr + 0, arr + 5);
// displaying list1
cout << "After assigning... " << endl;
cout << "Size of list1: " << list1.size() << endl;
cout << "Elements of list1: ";
dispList(list1);
return 0;
}
Output
Before assign...
Size of list1: 0
Elements of list1:
After assigning...
Size of list1: 5
Elements of list1: 10 20 30 40 50