Write a program that creates a list (STL list) of 100 random int values. Use the iterators to display all the values of the list in order and in reverse order. Use the sort function to sort the list of values and output the list. g

Respuesta :

Answer:

The program is as follows:

#include <bits/stdc++.h>

#include <iostream>

using namespace std;

int main(){

  list <int> myList;

  for(int i=0;i<100;i++){  

      myList.push_back(rand()%100);       }

   list <int> :: iterator it;

   cout<<"Forward: ";

   for(it = myList.begin(); it != myList.end(); ++it){

       cout <<*it<<" ";    }

   

   cout<<"\nReversed: ";

   std::copy(myList.rbegin(),myList.rend(),std::ostream_iterator<int>(std::cout, " "));

        myList.sort();  

   cout<<"\nSorted: ";

   for(it = myList.begin(); it != myList.end(); ++it){

       cout <<*it<<" ";    }

   return 0;

}

Explanation:

This declares the list

  list <int> myList;

The following iteration generates 100 random integers into the list

  for(int i=0;i<100;i++){  

      myList.push_back(rand()%100);       }

This initializes an iterator

   list <int> :: iterator it;

This prints the header "Forward"

   cout<<"Forward: ";

This iterates through the list and prints it in order

   for(it = myList.begin(); it != myList.end(); ++it){

       cout <<*it<<" ";    }

    This prints the header "Reversed"

   cout<<"\nReversed: ";

This uses ostream_iterator to print the reversed list

   std::copy(myList.rbegin(),myList.rend(),std::ostream_iterator<int>(std::cout, " "));

This sorts the list in ascending order

        myList.sort();

This prints the header "Reversed"  

   cout<<"\nSorted: ";

This iterates through the sorted list and prints it in order

   for(it = myList.begin(); it != myList.end(); ++it){

       cout <<*it<<" ";    }

ACCESS MORE