博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
文件Median.h
#include <list>
class CMedian
{
public:
    explicit CMedian();
    virtual ~CMedian();
    void getMedian(float& NumberOfMedian);

    std::list<float> array;
};
文件Median.cpp
#include "Median.h"

CMedian::CMedian()
{
}

CMedian::~CMedian()
{
}

void CMedian::getMedian(float& NumberOfMedian)
{
    array.sort();
    int n = array.size();
    std::list<float>::iterator itr = array.begin();
    for(int i = 0;i < n/2; ++i)
        itr++;
    if(0 == n % 2)
    {
        NumberOfMedian = (*itr + *(--itr)) / 2;
    }
    else
    {
        NumberOfMedian = *itr;
    }
}
文件:main.cpp
#include "Median.h"
#include <vector>
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    float a[4] = {3,1,9,5};
    float b[4] = {8,-1,6,3};
    float c[4] = {1,2,4,0};
    CMedian *array1 = new CMedian();
    CMedian *array2 = new CMedian();
    CMedian *array3 = new CMedian();
    CMedian *sumArray = new CMedian();
    for(int i = 0; i < 4;i++)
    {
        array1->array.push_back(a[i]);
    }
    for(int i = 0; i < 4;i++)
    {
        array2->array.push_back(b[i]);
    }
    for(int i = 0; i < 4;i++)
    {
        array3->array.push_back(c[i]);
    }

    float NumberOfMedian1 = 0;
    float NumberOfMedian2 = 0;
    float NumberOfMedian3 = 0;
    array1->getMedian(NumberOfMedian1);
    array2->getMedian(NumberOfMedian2);
    array3->getMedian(NumberOfMedian3);

    std::cout<<NumberOfMedian1<<std::endl;
    std::cout<<NumberOfMedian2<<std::endl;
    std::cout<<NumberOfMedian3<<std::endl;

    sumArray->array.push_back(NumberOfMedian1);
    sumArray->array.push_back(NumberOfMedian2);
    sumArray->array.push_back(NumberOfMedian3);

    float finalMedian = 0;
    sumArray->getMedian(finalMedian);
    std::cout<<finalMedian<<std::endl;
    std::cin>>finalMedian;
    return 0;
}

实际图

sshot-6