(SOLVED) Sort a vector Define a function named SortVector that takes a vector of integers as a parameter.
Discipline: IT, Web
Type of Paper: Question-Answer
Academic Level: Undergrad. (yrs 3-4)
Paper Format: APA
Pages: 1
Words: 275
Question
Sort a vector Define a function named SortVector that takes a vector of integers as a parameter. Function SortVector() modifies the vector parameter by sorting the elements in descending order (highest to lowest). Then write a main program that reads a list of integers from input, stores the integers in a vector, calls SortVector(), and outputs the sorted vector. The first input integer indicates how many numbers are in the list. Ex: If the input is: 5 10 4 39 12 2 the output is: 39,12,10,4,2, It must be done in C++
Expert Answer
The complete program source code, including the required functions, is given below:
#include
#include
#include
using namespace std;
//functon to display vector
void display(vector<int> vec)
{
for (auto i = vec.begin(); i != vec.end(); ++i)
{
cout << *i << ",";
}
}
void SortVector(vector<int> &vec)
{
//sort the vector
sort(vec.begin(), vec.end(), greater ());
}
//main function
int main()
{
//variable declaration
int length, num;
vector<int> v;
//display message
cin>>length;
//fill the vector with random value
for (int i = 1; i <= length; i++)
{
cin>>num;
v.push_back(num);
}
//call the method
SortVector(v);
//display the sorted vector
display(v);
return 0;
}
Explanation:
This program accepts a list of numbers and then displays the numbers in sorted order.
Step 2/2
Final answer
The output of the above program after execution is given below:
![Output](https://media1.cheggcdn.com/coop/7d7/7d709e98-ad9e-4d09-a92d-2c1a421a4330/output.png?u=74e8d097-30e4-42db-8eb9-25caf36c914a&q=734e59ef-261d-44a8-a2dd-a8ee3b01e005&context=gdg-qna-dgs&Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9tZWRpYTEuY2hlZ2djZG4uY29tL2Nvb3AvN2Q3LzdkNzA5ZTk4LWFkOWUtNGQwOS1hOTJkLTJjMWE0MjFhNDMzMC9vdXRwdXQucG5nP3U9NzRlOGQwOTctMzBlNC00MmRiLThlYjktMjVjYWYzNmM5MTRhJnE9NzM0ZTU5ZWYtMjYxZC00NGE4LWEyZGQtYThlZTNiMDFlMDA1JmNvbnRleHQ9Z2RnLXFuYS1kZ3MiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE2ODAzNTc4NjZ9LCJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTY4MDM1NTc2Nn19fV19&Key-Pair-Id=K1M1OMQ09SPKJC&Signature=AFKtk11T0P7poee7tyMAvh89jQzGGBSBU~mbbafGkyJmlrisIJkLfE3lUTThwx2iia1BhjqLgYE0Mv7iek9okO-L0ySFM0bNyTGD36eKEKzkRzOzR7nzzAYWgOuY9voO52r9j8060PUz7A8PRuM2s6YyKAk2gccuIKgCMy8NQr0rxcYKXjWJ0HwlZnDwE8kO~qRsb7BCdVf~yhVgnUavOzZteRf58dpWssEmzSw9mlm8qaq~Fesi6jdQlieK-Pq3zDCgF-YUTwXeX-rMlrizd8CyhMTB9zwsS8hpCtr0f0SvleeG6Y4OS-lYe76ReHNY30TMtg-U4e5fkRORQSKVPA__)
This output is as expected.