Aquí, vamos a aprender a asignar una lista con los elementos de una matriz en C ++ STL ?
Dada una matriz y que tiene que crear una lista, que debe asignarse con todos los elementos de la matriz mediante el programa C ++ (STL).
Ejemplo:
Aquí, estamos declarando una lista lista1 y una matriz arr , arr tiene 5 elementos, todos los elementos del arr está asignando a la lista lista1 mediante el uso de las declaraciones siguientes,
list1.assign(arr+0, arr+5);
Aquí,
- lista1 es una lista de tipo entero
- arr es una matriz de enteros
- arr + 0 puntos el primer elemento de la matriz
- Y, arr + 4 puntos el último elemento de la matriz
Programa:
#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;
}
salida
Before assign...
Size of list1: 0
Elements of list1:
After assigning...
Size of list1: 5
Elements of list1: 10 20 30 40 50