简体   繁体   中英

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. 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. It's not an array of int values, it's a std::vector<int> object, which is totally different.

Your call

findMedian(list1, n)

attempts to find the function double findMedian(std::vector<int>, int) , which doesn't exists.

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. I recommend the first solution.

A vector's size is simply v.size() , not what you wrote here

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM