以下是我在一个实现文件中编写的代码,用于计算双向量的中位数的函数:
#include<algorithm>
#include<stdexcept>
#include<vector>
#include "median.h"
using std::domain_error;
using std::vector;
double median(vector<double> vect)
{
typedef vector<double>::size_type vec_sz;
vec_sz size=vect.size();
if(size==0)
throw domain_error("median of an empty vector");
sort(vect.begin(),vect.end());
vec_sz mid= size/2;
return size%2==0 ? (vect[mid]+vect[mid-1])/2 : vect[mid];
}
当我在命令行上使用g ++ median.cpp编译它时,我得到以下内容:
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
该错误是因为您没有main
函数。创建一个main
函数并从main函数调用median
函数。
#include<algorithm>
#include<stdexcept>
#include<vector>
#include "median.h"
using std::domain_error;
using std::vector;
double median(vector<double> vect)
{
typedef vector<double>::size_type vec_sz;
vec_sz size=vect.size();
if(size==0)
throw domain_error("median of an empty vector");
sort(vect.begin(),vect.end());
vec_sz mid= size/2;
return size%2==0 ? (vect[mid]+vect[mid-1])/2 : vect[mid];
}
void main()
{
// call the median(vector<double> vect) function from here
vector<double> vect = {10,20,30}; // initialize with numbers
double retval = median(vect);
}