61.1k views
0 votes
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

User Lime
by
4.1k points

1 Answer

5 votes

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<<"\\Reversed: ";

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

myList.sort();

cout<<"\\Sorted: ";

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<<"\\Reversed: ";

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<<"\\Sorted: ";

This iterates through the sorted list and prints it in order

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

cout <<*it<<" "; }

User Vijay Rajput
by
4.5k points