2015年5月29日金曜日

numeric_limits(C++)

numeric_limitsは数値型の取りうる値の範囲についての情報を得るときに利用する。

以下のように使用する。

//
// limits.cpp
// CplusplusPractice
//
// Created by masai on 2015/05/19.
// Copyright (c) 2015年 masai. All rights reserved.
//
#include <iostream>
#include <limits>
typedef long HashValueLong;
typedef unsigned long HashValueULong;
int main() {
// マクロ定義による取得
std::cout << "int max: " << INT_MAX << std::endl;
std::cout << "int min: " << INT_MIN << std::endl;
// クラステンプレートによる取得
std::cout << "int max: " << std::numeric_limits<int>::max() << std::endl; //2147483647
std::cout << "long max: " << std::numeric_limits<long>::max() << std::endl; //2147483647
std::cout << "long min: " << std::numeric_limits<long>::min() << std::endl;
std::cout << "long lowest: " << std::numeric_limits<long>::lowest() << std::endl;
std::cout << "double max: " << std::numeric_limits<double>::max() << std::endl;
std::cout << "double min: " << std::numeric_limits<double>::min() << std::endl;
std::cout << "double lowest: " << std::numeric_limits<double>::lowest() << std::endl;
// 型に依存しない書き方
std::cout << "HashValue(long): " << std::numeric_limits<HashValueLong>::max() << std::endl;
std::cout << "HashValue(unsigned long): " << std::numeric_limits<HashValueULong>::max() << std::endl;
return 0;
}
最小値を得たい場合に注意が必要である。
min()は必ずしも-max()を返すわけではなく、整数型と浮動小数点型とで意味が異なる。
C++11からはlowest()を利用すると良い。

0 件のコメント:

コメントを投稿