是否有一个C ++跨平台库为我提供了一个可移植的最大整数?
我想声明:
const int MAX_NUM = /* call some library here */;
我使用MSVC 2008非托管。
答案 0 :(得分:92)
在C ++标准库标题<limits>
中,您将找到:
std::numeric_limits<int>::max()
这将告诉您可以存储在int
类型的变量中的最大值。 numeric_limits
是一个类模板,您可以将其传递给任何数字类型以获得它们可以容纳的最大值。
numeric_limits
类模板有很多other information about numeric types as well。
答案 1 :(得分:10)
请参阅limits.h
(C)或climits
(C ++)。在这种情况下,您希望INT_MAX
不变。
答案 2 :(得分:6)
我知道这是一个老问题,但也许有人可以使用这个解决方案:
GitHub
到目前为止,我们的结果为-1,直到size为signed int。
int size = 0; // Fill all bits with zero (0)
size = ~size; // Negate all bits, thus all bits are set to one (1)
正如标准所说,如果变量有符号且为负,则移入的位为1;如果变量为无符号或有符号且为正,则移位为0。
当大小有符号且为负时,我们会将符号位移1,这对于帮助不大,所以我们转换为无符号整数,强制转换为0,将符号位设置为0,同时让所有其他位保持1。
size = (unsigned int)size >> 1; // Shift the bits of size one position to the right.
我们也可以使用掩码和xor但是我们必须知道变量的确切位数。通过前移位,我们不必随时知道int在机器或编译器上有多少位,也不需要包含额外的库。
答案 3 :(得分:3)
我知道答案已经给出,但我只是想知道我过去的日子,我曾经做过
int max = (unsigned int)-1
它是否与
相同std::numeric_limits<int>::max()
答案 4 :(得分:1)
在具有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和long类型都是4bytes。 manpage limits(5)表示INT_MAX和LONG_MAX都是2147483647
http://nixdoc.net/man-pages/HP-UX/man5/limits.5.html
所以,结论std :: numeric_limits&lt; type&gt; ::不可移植。