std:: numeric_limits
Provides information about the properties of arithmetic types (either integral or floating-point) in the specific platform for which the library compiles.
This class template is specialized for every fundamental arithmetic type, with its members describing the properties of type T . This template shall not be specialized for any other type.
Template parameters
T A type.
If this is a fundamental arithmetic type, the members of the class describe its properties.
Template instantiations
fundamental arithmetic types | |
---|---|
integral types | bool |
char | |
wchar_t | |
signed char | |
short int | |
int | |
long int | |
unsigned char | |
unsigned short int | |
unsigned int | |
unsigned long int | |
floating point types | float |
double | |
long double |
For any other type, its default definition is used.
fundamental arithmetic types | |
---|---|
integral types | bool |
char | |
char16_t | |
char32_t | |
wchar_t | |
signed char | |
short int | |
int | |
long int | |
long long int | |
unsigned char | |
unsigned short int | |
unsigned int | |
unsigned long int | |
unsigned long long int | |
floating point types | float |
double | |
long double |
This template is also specialized for all const and/or volatile qualifications of these types, with the same values as their unqualified specializations.
For any other type, its default definition is used.
Members that produce a value of type T are member functions, while members of specific types are static member constants:
Members
member | type | property |
---|---|---|
is_specialized | bool | true for all arithmetic types (i.e., those for which numeric_limits is specialized). false for all other types. |
min() | T | Minimum finite value. For floating types with denormalization (variable number of exponent bits): minimum positive normalized value. Equivalent to CHAR_MIN , SCHAR_MIN , SHRT_MIN , INT_MIN , LONG_MIN , LLONG_MIN , FLT_MIN , DBL_MIN , LDBL_MIN or 0 , depending on type. |
max() | T | Maximum finite value. Equivalent to CHAR_MAX , SCHAR_MAX , UCHAR_MAX , SHRT_MAX , USHRT_MAX , INT_MAX , UINT_MAX , LONG_MAX , ULONG_MAX , LLONG_MAX , ULLONG_MAX , UINT_LEAST16_MAX , UINT_LEAST32_MAX , FLT_MAX , DBL_MAX or LDBL_MAX , depending on type. |
lowest() | T | Minimum finite value. (since C++11) For integral types: the same as min() . For floating-point types: implementation-dependent; generally, the negative of max() . |
digits | int | For integer types: number of non-sign bits ( radix base digits) in the representation. For floating types: number of digits (in radix base) in the mantissa (equivalent to FLT_MANT_DIG , DBL_MANT_DIG or LDBL_MANT_DIG ). |
digits10 | int | Number of digits (in decimal base) that can be represented without change. Equivalent to FLT_DIG , DBL_DIG or LDBL_DIG for floating types. |
max_digits10 | int | Number of digits (in decimal base) required to ensure that values that differ are always differentiated. |
is_signed | bool | true if type is signed. |
is_integer | bool | true if type is integer. |
is_exact | bool | true if type uses exact representations. |
radix | int | For integer types: base of the representation. For floating types: base of the exponent of the representation (equivalent to FLT_RADIX ). |
epsilon() | T | Machine epsilon (the difference between 1 and the least value greater than 1 that is representable). Equivalent to FLT_EPSILON , DBL_EPSILON or LDBL_EPSILON for floating types. |
round_error() | T | Measure of the maximum rounding error. |
min_exponent | int | Minimum negative integer value such that radix raised to (min_exponent-1) generates a normalized floating-point number. Equivalent to FLT_MIN_EXP , DBL_MIN_EXP or LDBL_MIN_EXP for floating types. |
min_exponent10 | int | Minimum negative integer value such that 10 raised to that power generates a normalized floating-point number. Equivalent to FLT_MIN_10_EXP , DBL_MIN_10_EXP or LDBL_MIN_10_EXP for floating types. |
max_exponent | int | Maximum integer value such that radix raised to (max_exponent-1) generates a representable finite floating-point number. Equivalent to FLT_MAX_EXP , DBL_MAX_EXP or LDBL_MAX_EXP for floating types. |
max_exponent10 | int | Maximum integer value such that 10 raised to that power generates a normalized finite floating-point number. Equivalent to FLT_MAX_10_EXP , DBL_MAX_10_EXP or LDBL_MAX_10_EXP for floating types. |
has_infinity | bool | true if the type has a representation for positive infinity. |
has_quiet_NaN | bool | true if the type has a representation for a quiet (non-signaling) «Not-a-Number». |
has_signaling_NaN | bool | true if the type has a representation for a signaling «Not-a-Number». |
has_denorm | float_denorm_style | Denormalized values (representations with a variable number of exponent bits). A type may have any of the following enum values: denorm_absent , if it does not allow denormalized values. denorm_present , if it allows denormalized values. denorm_indeterminate , if indeterminate at compile time. |
has_denorm_loss | bool | true if a loss of accuracy is detected as a denormalization loss, rather than an inexact result. |
infinity() | T | Representation of positive infinity, if available. |
quiet_NaN() | T | Representation of quiet (non-signaling) «Not-a-Number», if available. |
signaling_NaN() | T | Representation of signaling «Not-a-Number», if available. |
denorm_min() | T | Minimum positive denormalized value. For types not allowing denormalized values: same as min() . |
is_iec559 | bool | true if the type adheres to IEC-559 / IEEE-754 standard. An IEC-559 type always has has_infinity , has_quiet_NaN and has_signaling_NaN set to true ; And infinity , quiet_NaN and signaling_NaN return some non-zero value. |
is_bounded | bool | true if the set of values represented by the type is finite. |
is_modulo | bool | true if the type is modulo. A type is modulo if it is possible to add two positive numbers and have a result that wraps around to a third number that is less. |
traps | bool | true if trapping is implemented for the type. |
tinyness_before | bool | true if tinyness is detected before rounding. |
round_style | float_round_style | Rounding style. A type may have any of the following enum values: round_toward_zero , if it rounds toward zero. round_to_nearest , if it rounds to the nearest representable value. round_toward_infinity , if it rounds toward infinity. round_toward_neg_infinity , if it rounds toward negative infinity. round_indeterminate , if the rounding style is indeterminable at compile time. |
For all types that are not fundamental arithmetic types, the default template definition is used:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
template class T> class numeric_limits < public: static const bool is_specialized = false; static T min() throw(); static T max() throw(); static const int digits = 0; static const int digits10 = 0; static const bool is_signed = false; static const bool is_integer = false; static const bool is_exact = false; static const int radix = 0; static T epsilon() throw(); static T round_error() throw(); static const int min_exponent = 0; static const int min_exponent10 = 0; static const int max_exponent = 0; static const int max_exponent10 = 0; static const bool has_infinity = false; static const bool has_quiet_NaN = false; static const bool has_signaling_NaN = false; static const float_denorm_style has_denorm = denorm_absent; static const bool has_denorm_loss = false; static T infinity() throw(); static T quiet_NaN() throw(); static T signaling_NaN() throw(); static T denorm_min() throw(); static const bool is_iec559 = false; static const bool is_bounded = false; static const bool is_modulo = false; static const bool traps = false; static const bool tinyness_before = false; static const float_round_style round_style = round_toward_zero; >;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
template class T> class numeric_limits < public: static constexpr bool is_specialized = false; static constexpr T min() noexcept < return T(); > static constexpr T max() noexcept < return T(); > static constexpr T lowest() noexcept < return T(); > static constexpr int digits = 0; static constexpr int digits10 = 0; static constexpr bool is_signed = false; static constexpr bool is_integer = false; static constexpr bool is_exact = false; static constexpr int radix = 0; static constexpr T epsilon() noexcept < return T(); > static constexpr T round_error() noexcept < return T(); > static constexpr int min_exponent = 0; static constexpr int min_exponent10 = 0; static constexpr int max_exponent = 0; static constexpr int max_exponent10 = 0; static constexpr bool has_infinity = false; static constexpr bool has_quiet_NaN = false; static constexpr bool has_signaling_NaN = false; static constexpr float_denorm_style has_denorm = denorm_absent; static constexpr bool has_denorm_loss = false; static constexpr T infinity() noexcept < return T(); > static constexpr T quiet_NaN() noexcept < return T(); > static constexpr T signaling_NaN() noexcept < return T(); > static constexpr T denorm_min() noexcept < return T(); > static constexpr bool is_iec559 = false; static constexpr bool is_bounded = false; static constexpr bool is_modulo = false; static constexpr bool traps = false; static constexpr bool tinyness_before = false; static constexpr float_round_style round_style = round_toward_zero; >;
All specializations shall also provide these values as constant expressions.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
// numeric_limits example // std::cout // std::numeric_limits int main () < std::cout "Minimum value for int: " int>::min() '\n'; std::cout "Maximum value for int: " int>::max() '\n'; std::cout "int is signed: " int>::is_signed '\n'; std::cout "Non-sign bits in int: " int>::digits '\n'; std::cout "int has infinity: " int>::has_infinity '\n'; return 0; >
Possible output:
Minimum value for int: -2147483648 Maximum value for int: 2147483647 int is signed: true Non-sign bits in int: 31 int has infinity: false
See also
(limits.h) Sizes of integral types (header) (float.h) Characteristics of floating-point types (header)
std::numeric_limits::digits
Значение std::numeric_limits::digits — это количество цифр в базе- radix , которое может быть представлено типом T без изменений. Для целочисленных типов это количество битов, не считая бита знака и битов заполнения (если any). Для типов с плавающей запятой, это цифры мантиссы (для реализаций IEC 559/IEEE 754 это количество цифр, сохраненных для мантиссы, плюс один, потому что мантисса имеет неявную ведущую 1 и двоичную point).
Standard specializations
T | значение std::numeric_limits::digits (при условии отсутствия padding bits ) |
---|---|
/* неспециализированный */ | 0 |
bool | 1 |
char | CHAR_BIT — std::numeric_limits::is_signed |
signedchar | CHAR_BIT — 1 |
unsignedchar | CHAR_BIT |
wchar_t | CHAR_BIT * sizeof(wchar_t) |
std::numeric_limits
Шаблон класса std::numeric_limits предоставляет стандартизированный способ запроса различных свойств арифметических типов (e.g. (максимальное возможное значение для типа int — std::numeric_limits::max() ).
Эта информация предоставляется через специализации шаблона std::numeric_limits . standard library делает доступными специализации для всех типов арифметики (перечислены только специализации для cv-unqualified арифметики types):).
template<> class numeric_limitsbool>;
template<> class numeric_limitschar>;
template<> class numeric_limitssigned char>;
template<> class numeric_limitsunsigned char>;
template<> class numeric_limitswchar_t>;
template<> class numeric_limitschar8_t>;
template<> class numeric_limitschar16_t>;
template<> class numeric_limitschar32_t>;
template<> class numeric_limitsshort>;
template<> class numeric_limitsunsigned short>;
template<> class numeric_limitsint>;
template<> class numeric_limitsunsigned int>;
template<> class numeric_limitslong>;
template<> class numeric_limitsunsigned long>;
template<> class numeric_limitslong long>;
template<> class numeric_limitsunsigned long long>;
template<> class numeric_limitsfloat>;
template<> class numeric_limitsdouble>;
template<> class numeric_limitslong double>;
Значение каждого члена специализации std::numeric_limits для типа с указанием cv cv T равно значению соответствующего члена специализации на неквалифицированном типе T . Например, std::numeric_limits::digits равно std::numeric_limits::digits .
Псевдонимы арифметических типов (например, std::size_t или std::streamsize ) также могут быть исследованы с признаками типа std::numeric_limits .
Неарифметические стандартные типы, такие как std::complex или std::nullptr_t , не имеют специализаций.
Если реализация определяет какие-либо integer-class types , для них также должны быть предоставлены специализации std::numeric_limits .
Реализации могут предоставлять специализации std::numeric_limits для конкретных типов реализации: например, GCC предоставляет std::numeric_limits . Нестандартный libraries может использовать add specializations для типов, предоставляемых library, например OpenEXR предоставляет std::numeric_limits для 16-битного типа с плавающей запятой.
Template parameters
T | — | тип для получения числовых свойств для |
Why doesn’t it work properly, Numeric_limits
I have a function with two arguments, a vector whose elements are being tested, and a bool variable that we enter as true or false. If we enter true then it is supposed to isolate and place all the elements whose sum of digits is an even number to a new vector (in the same order they came) and return that vector. With false it’s the opposite, odd numbers. And you can only use pretty much the things I have already used here, nothing else. This is how it looks.
std::vector IzdvojiElemente(std::vector v, bool flag) < std::vectorn; for(int i(0); i0) < suma+=temp%10; temp/=10; >if(flag && suma%2==0) n.push_back(v[i]); if(!flag && suma%2!=0) n.push_back(v[i]); > return n; >
And this is one of the main functions for which it doesn’t work:
std::vector v1 <1,std::numeric_limits::min(),2, std::numeric_limits::max(),5>; std::vector v2; v2 = IzdvojiElemente(v1, false); for(int i=0; i < v2.size(); i++) std::cout
This is what I was supposed to get (as output):
1 -2147483648 5
This is what I got:
For some reason it either ignores the numeric limits, or doesn't but sorts them with the wrong vector. And I don't know why. In any other cases it works as it should. And maybe it's overflow, but I can't see where.