Accelerated C++ Exercise 10-2,3

本文介绍了一个使用C++实现的通用中位数计算函数,该函数能够处理数组和vector两种数据结构,并通过实例展示了其用法。
#include <algorithm>
#include <stdexcept>
#include <vector>
#include <iostream>

using std::domain_error;
using std::sort;
using std::cout;
using std::endl;
using std::vector;

template <class T, class Iterator>
T median(Iterator begin, Iterator end) {
  if (begin == end)
    throw domain_error("median of an empty container");
  
  vector<T> temp;
  
  for ( ; begin != end; ++begin)
    temp.push_back(*begin);

  sort(temp.begin(), temp.end());

  size_t mid = temp.size() / 2;

  T ret = (temp.size() % 2 == 0)
    ? (temp[mid] + temp[mid - 1]) / 2
    : temp[mid];

  return ret;
}

int main() {
  int test_arr[] = {1, 2, 8, 4, 5, 6, 7, 3, 9, 10};
  vector<int> test_vec(test_arr, test_arr + 10);

  cout << "Median: " << median<int>(test_arr, test_arr + 10) << endl;

  for (int i = 0; i < 10; ++i)
    cout << test_arr[i] << endl;;

  cout << "Median: " << median<int>(test_vec.begin(), test_vec.end()) << endl;

  for (int i = 0; i < 10; ++i)
    cout << test_vec[i] << endl;
  system("pause");
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值