C ++:最大整数
是否有一个C ++跨平台库,为我提供了一个可移植的最大整数数字?
我想宣布:
const int MAX_NUM = /* call some library here */; 我使用MSVC 2008非托pipe。
 在C ++标准库头<limits> ,您将find: 
 std::numeric_limits<int>::max() 
 这将告诉你可以存储在inttypes的variables中的最大值。  numeric_limits是一个类模板,您可以将其传递给任何数字types以获得它们可以容纳的最大值。 
  numeric_limits类模板也有很多关于数字types的其他信息 。 
 参见limits.h (C)或climits (C ++)。 在这种情况下,你会想要INT_MAX常量。 
我知道这是一个老问题,但也许有人可以使用这个解决scheme:
 int size = 0; // Fill all bits with zero (0) size = ~size; // Negate all bits, thus all bits are set to one (1) 
到目前为止,我们有-1作为结果'直到大小是一个有符号整数。
 size = (unsigned int)size >> 1; // Shift the bits of size one position to the right. 
正如标准所述,如果variables是有符号的,则移入的位是1,否则是0,如果variables是无符号或有符号的,则为0。
因为大小是有符号的,而且是负的,所以我们将符号位移到1,这对我们没有太大的帮助,所以我们把它转换为无符号整数,强制移入0,而将所有其他位保留为1。
 cout << size << endl; // Prints out size which is now set to maximum positive value. 
我们也可以使用mask和xor,但是我们必须知道variables的精确比特。 随着位移,我们不必知道int在机器或编译器上有多less位,也不需要包含额外的库。
我知道答案已经给出,但我只想从我以前的事情知道,我曾经这样做过
 int max = (unsigned int)-1 
它会给与一样的
 std::numeric_limits<int>::max() 
?
在使用aCC编译器的Hp UX上:
 #include <iostream> #include <limits> using namespace std; int main () { if (sizeof(int)==sizeof(long)){ cout<<"sizeof int == sizeof long"<<endl; } else { cout<<"sizeof int != sizeof long"<<endl; } if (numeric_limits<int>::max()==numeric_limits<long>::max()){ cout<<"INT_MAX == lONG_MAX"<<endl; } else { cout<<"INT_MAX != LONG_MAX"<<endl; } cout << "Maximum value for int: " << numeric_limits<int>::max() << endl; cout << "Maximum value for long: " << numeric_limits<long>::max() << endl; return 0; } 
它打印:
sizeof int == sizeof long
INT_MAX!= LONG_MAX
我检查了int和longtypes都是4字节。 (5)表示,INT_MAX和LONG_MAX都是2147483647
http://nixdoc.net/man-pages/HP-UX/man5/limits.5.html
所以,结论std :: numeric_limits <type> ::不是可移植的。