Please write a C++ function called reverse() and it should have one incoming arg
ID: 3766797 • Letter: P
Question
Please write a C++ function called reverse() and it should have one incoming argument: an integer vector. This function should rearrange the values in the incoming vector so that they are in reverse order when control is returned to the calling statement. For example, if the incoming vector is with values: a[0] has 10 and a[1] has 20. Then after this function has been called, a[0] should has 20 and a[1] should have 10 inside.
Please write a C++ function main() that will do the following:
1. Prompt the use for non-negative numeric integer values (e.g., 0, 1, 20, 300..., etc.) and receive them one by one (you can assume that the user will key in non-negative numeric integer values and no input validation is needed for Homework 1).
2. Read these input values into a vector.
3. Display these values received from the user in the correct order.
4. Call function reverse() to re-arrange the values inside this vector.
5. Display the values inside this vector after calling reverse() in Step 4. The values displayed should be in reverse order of the entry in Step 2.
6. Finally, the system displays the message “Bye!” and the window stays on the screen until the user closes it.
Explanation / Answer
Sample code:
Sample output:
Code to copy:
// ReversalOfVector.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
using namespace std;
#include <vector>
void reverseOrder(vector<int> v1);
int main()
{
int x,size;
std::vector<int> Vector;
cout<<"enter the size of the vector"<<endl;
cin>>size;//prompt the user for the size of the vector
for (int i=0; i<size; i++)
{
cout<<"input element"<<i+1<<":";
cin>>x;//read elements into vector
Vector.push_back(x);
}
cout<<"Reverse order of the vector elements"<<endl;
reverseOrder(Vector);//call the function reverseOrder(Vector);
cout<<"Bye!";
system("pause");
return 0;
}
void reverseOrder(vector<int> v1)//reverseOrder(Vector) function definiton
{
reverse(v1.begin(),v1.end());
for (vector<int>::iterator itr=v1.begin(); itr!=v1.end(); ++itr)
cout << ' ' << *itr;
cout << ' ';
}