C++ STL: The std::numeric_limits Class

De Wiki de Calcul Québec
Aller à : Navigation, rechercher
Cette page est une traduction de la page C++ STL : la classe std::numeric limits et la traduction est complétée à 100 % et à jour.

Autres langues :anglais 100% • ‎français 100%

The class std::numeric_limits<T> is part of the STL (Standard Template Library). It provides us with the principal characteristics of the basic numerical types (int, long, double etc.). It offers a standard, compiler-independent interface for obtaining the implementation details associated with numerical types. Using this library increases the code's portability and can make it more expressive. Methods like min(), max(), infinity() and epsilon allow the programmer to know and express unambiguously the limits of a numerical representation.

The following example shows min() and max() at work:


File : std_numeric_limits_example.cpp
#include <limits>
#include <vector>
 
using namespace std;
 
// Shrink a vector by converting its elements to a shorter type.
// NOTE: valid for integral types only
template <class TLong, class TShort>
bool reduceSize(const vector<TLong>& input, vector<TShort>& output)
{
    for (size_t i = 0; i < input.size(); ++i)
    {
        if (input[i] >= (TLong)numeric_limits<TShort>::min() &&
            input[i] <= (TLong)numeric_limits<TShort>::max())
        {
            output.push_back((TShort)input[i]);
        }
        else
        {
            // The element does not fit in the target type.
            return false;
        }
    }
 
    // All the elements were converted succesfully.
    return true;
}


Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Ressources de Calcul Québec
Outils
Partager