Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ Programming help: Implement code to sort the vector of numeric values below

ID: 3866835 • Letter: C

Question

C++ Programming help: Implement code to sort the vector of numeric values below :

#include <iostream>

#include <algorithm>

#include <vector>

// Prints all elements in a vector

template <typename T>

void PrintVector(vector<T> a)

{

    for (size_t i = 0; i < a.size(); i++)

        cout << a[i] << " ";

    cout << endl;

}

int main()

{

    double values[] = { 32.0, 71.0, 12.0, 45.0, 26.0, 80.0, 53.0, 33.0 };

    std::vector<double> myvector(values, values + 8);

    cout << "UNSORTED ARRAY:" << endl;

    PrintVector<double>(myvector);

    cout << endl;

  // TODO: Add code below this line to sort the “values” array of double(s) above.

    cout << "SORTED ARRAY:" << endl;

    PrintVector<double>(myvector);

    cout << endl;

    return 0;

}

Explanation / Answer

Program:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// Prints all elements in a vector
template <typename T>
void PrintVector(vector<T> a)
{
for (size_t i = 0; i < a.size(); i++)
cout << a[i] << " ";
cout << endl;
}

int main()
{
double values[] = { 32.0, 71.0, 12.0, 45.0, 26.0, 80.0, 53.0, 33.0 };
std::vector<double> myvector(values, values + 8);

cout << "UNSORTED ARRAY:" << endl;
PrintVector<double>(myvector);
cout << endl;
  
int n = sizeof(values)/sizeof(values[0]); // The code will find the size of the array

sort(values, values+n); // It will sort the values in the array
  
std::vector<double> sortedmyvector(values, values + 8); // We are assigning the array values to vector
  
cout << "SORTED ARRAY:" << endl;
PrintVector<double>(sortedmyvector); // Displaying the sorted vector
cout << endl;

return 0;
}

Output:

UNSORTED ARRAY:

32 71 12 45 26 80 53 33

SORTED ARRAY:

12 26 32 33 45 53 71 80

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote