Question

I am so close to finishing this program. It will find the median of an array of 5 values. I have one last error that I cannot seem to get to go away. Since I am new to C++, I have no idea of what the problem could be. I researched the error over and over on here and Google; no luck.

Here's the code:

#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
using namespace std; 

int main()
{ 
    int integer1, integer2, integer3, integer4, integer5;

//Input of integers
std::cout << "Enter the first integer: "; 
std::cin >> integer1; 
std::cout << "Enter the second integer: "; 
std::cin >> integer2; 
std::cout << "Enter the third integer: "; 
std::cin >> integer3; 
std::cout << "Enter the fourth integer:";
std::cin >> integer4;
std::cout << "Enter the fifth integer:";
std::cin >> integer5;

std::array <int,5> a = {integer1, integer2, integer3, integer4, integer5}; 

//Sort array
std::sort(a.begin(), a.end());
for (int a : a) {
        std::cout << a << " ";
}

std::nth_element(a.begin(), a.begin()+1, a.size()/2, a.end());
std::cout <<"The median of the integers "<<integer1<<", "<<integer2<<", "<<integer3<<", "<<integer4<<", and "<<integer5<< " is " <<a[a.size()/2]<< '\n';
std::endl (std::cout);



return 0; 
}

The error states: "IntelliSense: no instance of overloaded function "std::nth_element" matches the argument list, argument types are: (std::_Array_iterator, std::_Array_iterator, unsigned int, std::_Array_iterator)

Help me finish this thing! Thanks in advance.

Was it helpful?

Solution

You misunderstand what nth_element does, and are trying to use it incorrectly.

This function takes a range which is not necessarily sorted, and partially sorts it such that nth element is in its correct place. If you ise this function to find a median, you don't need to sorf first.

If you already have a sorted range [first, last) then nth element of this range is pointed to by first + n.

OTHER TIPS

I think you meant:

std::nth_element(a.begin(), a.begin()+a.size()/2, a.end()); 

Please refer to the c++ reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top