In C++ write a function object that compares two numbers and returns true if the first number is larger than the second number, and false otherwise. Use it to sort a vector of integers in descending order.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool compare (int a, int b)
{
if (a > b )
return true;
else
return false;
}
int main()
{
vector<int> vect{ 1, 5, 8, 9,
3,25,7,11}; //Sample vector
int vector_size = vect.size();
// storing the size of vector into
vector_size
int arr[vector_size], temp;
for (int i=0; i<vector_size-1 ;
i++)
{
for (int j=0;
j< vector_size-i; j++)
{
bool comp = compare(vect[j],vect[j+1]); // assigning the output of
function to variable comp
if ( comp == false)
// if comp is false
then
{
temp=vect[j];
//asigining the value of vect at j location to
temp variable
vect[j]=vect[j+1];
//swapping the values
vect[j+1]=temp;
//swapping the values
}
}
}
for (int i=0; i <=
vector_size-1 ; i++)
{
cout << vect[i] << endl;
//Printing the output of sorted vector
}
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.