日期:2014-05-20  浏览次数:20907 次

#indef是什么来的?
这是Accelerated   C++第四章median.cpp的源代码

//   source   file   for   the   `median '   function
#include   <algorithm>         //   to   get   the   declaration   of   `sort '
#include   <stdexcept>         //   to   get   the   declaration   of   `domain_error '
#include   <vector>               //   to   get   the   declaration   of   `vector '

using   std::domain_error;       using   std::sort;       using   std::vector;

#include   "median.h "

//   compute   the   median   of   a   `vector <double> '
//   note   that   calling   this   function   copies   the   entire   argument   `vector '
double   median(vector <double>   vec)
{
#ifdef   _MSC_VER
typedef   std::vector <double> ::size_type   vec_sz;
#else
typedef   vector <double> ::size_type   vec_sz;
#endif

vec_sz   size   =   vec.size();
if   (size   ==   0)
throw   domain_error( "median   of   an   empty   vector ");

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

vec_sz   mid   =   size/2;

return   size   %   2   ==   0   ?   (vec[mid]   +   vec[mid-1])   /   2   :   vec[mid];
}

请问一下这段代码是什么意思?有什么用?

#ifdef   _MSC_VER
typedef   std::vector <double> ::size_type   vec_sz;
#else
typedef   vector <double> ::size_type   vec_sz;
#endif


------解决方案--------------------
#ifdef 是预编译宏,在编译期就存在。

下面那段代码则是如果定义了_MSC_VER,就使用typedfe定义一个别名,这个别名使用注明名字空间的语法定义一个vector大小的类型。通常是因为没有引入std标准库或者内部已有vector类型,为了加以区别使用哪个vector的原因。