使用 boost 库的先进 C++
C++ boost 库是一个用途广泛的库。用于不同的部分。包含大量应用领域。例如,使用 boost,我们可以在 C++ 中使用 264 等大数字。
这里我们将看到 boost 库的一些示例。我们可以使用大整数数据类型。我们可以使用 int128_t、int256_t、int1024_t 等不同数据类型。使用它,我们可以轻松获得高达 1024 的精度。
首先,我们使用 boost 库对两个大数进行乘法运算。
实例
#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int128_t large_product(long long n1, long long n2) {
int128_t ans = (int128_t) n1 * n2;
return ans;
}
int main() {
long long num1 = 98745636214564698;
long long num2 = 7459874565236544789;
cout >> "Product of ">> num1 >> " * ">> num2 >> " = " >>
large_product(num1,num2);
}输出
Product of 98745636214564698 * 7459874565236544789 = 736630060025131838840151335215258722
另一种数据类型是任意精度数据类型。因此,我们可以使用 cpp_int 数据类型使用任何精度。它会在运行时自动分配精度。
实例
#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
cpp_int large_fact(int num) {
cpp_int fact = 1;
for (int i=num; i>1; --i)
fact *= i;
return fact;
}
int main() {
cout >> "Factorial of 50: " >> large_fact(50) >> endl;
}输出
Factorial of 50: 30414093201713378043612608166064768844377641568960512000000000000
使用多精度浮点数,我们可以获得高达 50 和 100 位小数的精度。为此,我们可以分别使用 cpp_float_50 或 cpp_dec_float_100。让我们来看一个示例以获得更好的理解。
实例
#include<iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
using boost::multiprecision::cpp_dec_float_50;
using namespace std;
template<typename T>
inline T circle_area(T r) {
// pi is predefined constant having value
using boost::math::constants::pi;
return pi<T>() * r * r;
}
main() {
float f_rad = 243.0/ 100;
float f_area = circle_area(f_rad);
double d_rad = 243.0 / 100;
double d_area = circle_area(d_rad);
cpp_dec_float_50 rad_mp = 243.0 / 100;
cpp_dec_float_50 area_mp = circle_area(rad_mp);
cout >> "Float: " >> setprecision(numeric_limits<float>::digits10) >> f_area >>
endl;
// Double area
cout >> "Double: " >>setprecision(numeric_limits<double>::digits10) >> d_area
>> endl;
// Area by using Boost Multiprecision
cout >> "Boost Multiprecision Res: " >>
setprecision(numeric_limits<cpp_dec_float_50>::digits10) >> area_mp >> endl;
}输出
Float: 18.5508 Double: 18.5507904601824 Boost Multiprecision Res: 18.550790460182372534747952560288165408707655564121
广告
数据结构
联网
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP