错误:nth_element-没有重载函数实例(中位数查找程序)



我马上就要完成这个节目了。它将找到一个包含5个值的数组的中位数。我还有最后一个无法消除的错误。由于我是c++的新手,我不知道问题可能是什么。我在这里和谷歌上一遍又一遍地研究这个错误;没有运气。

代码如下:

#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; 
}

错误提示:"智能提示:没有重载函数"std::nth_element"的实例匹配实参列表,实参类型为:(std::_Array_iterator, std::_Array_iterator, unsigned int, std::_Array_iterator)

帮我完成这件事!

您误解了nth_element的作用,并试图错误地使用它。

该函数接受一个不一定排序的范围,并对其进行部分排序,使第n个元素位于正确的位置。如果你使用这个函数来查找中值,你不需要先排序。

如果你已经有一个排序的范围[first, last),那么这个范围的第n个元素是由first + n指向的。

我想你的意思是:

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

请参考c++参考资料

最新更新