如何计算两个size_t变量的最大值

时间:2010-11-19 20:53:50

标签: c++ gcc max stdvector

我的代码中有这个。

vector<unsigned int> import;
vector<unsigned int> aquired;
. . .
size_t new_size = max(import.size(),aquired.size());

我收到此错误:

 error: more than one instance of
 overloaded function "max" matches the
 argument list:
             function "max(int, int)"
             function "max(unsigned int, unsigned int)"
             function "max(int, unsigned int)"
             function "max(unsigned int, int)"
             function "max(long long, long long)"
             function "max(unsigned long long, unsigned long long)"
             function "max(long long, unsigned long long)"
             function "max(unsigned long long, long long)"
             function "max(float, float)"
             function "max(double, double)"
             function "max(float, double)"
             function "max(double, float)"
             argument types are: (size_t, size_t)

我的理解是size_t是一个unsigned int。那么为什么这是一个问题,我该如何解决它。

编译:

$gcc --version
gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3
$nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2010 NVIDIA Corporation
Built on Wed_Sep__8_17:12:45_PDT_2010
Cuda compilation tools, release 3.2, V0.2.1221

4 个答案:

答案 0 :(得分:11)

#include <algorithm>

size_t val1;
size_t val2;

size_t maxValue = std::max<size_t>(val1, val2);

答案 1 :(得分:2)

size_t不一定是unsigned int,它取决于平台。如果您正在编译32位,或者如果您知道向量的大小将低于40亿,则可以安全地转换为unsigned int。一些64位平台使用64位size_t,但是只有32位的unsigned int 尝试使用此代替当前代码:

size_t new_size = max((unsigned int)import.size(),(unsigned int)aquired.size());

答案 2 :(得分:2)

我认为size_t实际上不是unsigned int。我怀疑它是它自己的类型,而不是typedef - 至少在g ++中

使用std :: max:

#include <algorithm>

int main(int argc, char **argv)
{
  size_t a = 2, b=3;
  std::max(a,b);
  return 0;
}

答案 3 :(得分:-1)

试试这个:

std::max((unsigned int)import.size(), (unsigned int)aquired.size());