[英]Finding the median of a vector
I have a function for finding the median of a array, but for some reason I get the message that the function could not be found when printing out the result.我有一个 function 用于查找数组的中位数,但由于某种原因,我收到一条消息,即在打印结果时找不到 function。 I think it has something to do with the fact that the array is stored in a vector, but I'm still stuck.我认为这与数组存储在向量中的事实有关,但我仍然卡住了。
#include <iostream>
#include <vector>
#include <algorithm>
double findMedian(int list1[], int n)
{
std::sort(list1, list1+n);
if (n % 2 != 0)
return (double)list1[n/2];
return (double)(list1[(n-1)/2] + list1[n/2])/2.0;
}
int main() {
std::vector<int> list1;
int n = sizeof(list1)/sizeof(list1[0]);
int number;
float sum=0;
int count=0;
int avg;
std::cin >> number;
list1.push_back(number);
sum = sum + number;
avg = sum/count;
while (number != 0){
std::cin >> number;
list1.push_back(number);
count++;
sum = sum + number;
avg = sum/count;
}
list1.pop_back();
std::sort(list1.begin(), list1.end(), std::greater<int>());
std::cout << "Average: \n" << avg << std::endl;
std::cout << "Median: " << findMedian(list1, n) << std::endl;
std::cout << "Sorted descending: \n";
for (auto x : list1)
std::cout << x << " ";
return 0;
}
Your problem is that you treat the std::vector
object list1
as an array.您的问题是您将std::vector
object list1
视为数组。 It's not an array of int
values, it's a std::vector<int>
object, which is totally different.它不是一个int
值数组,它是一个std::vector<int>
object,这是完全不同的。
Your call你的来电
findMedian(list1, n)
attempts to find the function double findMedian(std::vector<int>, int)
, which doesn't exists.试图找到不存在的 function double findMedian(std::vector<int>, int)
。
You can solve this either by changing findMedian
function to actually accept a vector as argument (and then it doesn't need the size), or by passing a pointer to the vector data.您可以通过更改findMedian
function 以实际接受向量作为参数(然后它不需要大小)或传递指向向量数据的指针来解决此问题。 I recommend the first solution.我推荐第一个解决方案。
A vector's size is simply v.size()
, not what you wrote here向量的大小只是v.size()
,而不是你在这里写的
int n = sizeof(list1)/sizeof(list1[0]);
This call should be changed from这个调用应该从
findMedian(list1, n)
to至
findMedian(list1.data(), n)
because a vector is not an array.因为向量不是数组。
Correct these and your code will work.更正这些,您的代码将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.