STL之complex

 

complex是一个类模板,实现了复数;

它有两个private成员变量,一个实部,一个虚部,它们的类型都是_Tp。
complex类中还包括或涉及这些部分:

  • typedef _Tp value_type
  • 构造函数
  • real函数返回实部,imag函数返回虚部
  • 重载了一些数学函数,如abs,log,sqrt等
  • 重载了一些运算符,包括=,+=,-=,*=, /=,+,-,*,/,==,!=,<<,>>

complex类对float,double,long double做了specialization。将_Tp实例化为除float, double,long double之外的类型的行为是未定义的。

#include <iostream>
#include <complex>
 
using namespace std;
 
int main()
{
    #ifndef ONLINE_JUDGE
        //freopen("d:\\OJ\\uva_in.txt", "r", stdin);
    #endif // ONLINE_JUDGE
    
    complex<double> c1(4.0, 3.0);
    
    complex<float> c2(polar(5.0, 0.75));
    
    cout << "c1:" << c1 << endl;
    cout << "c2:" << c2 << endl;
    // c1:(4,3)
    // c2:(3.65844,3.40819)
    
    cout << "c1:magnitude: " << abs(c1) 
         << " (squred magnitude: " << norm(c1) << ") "
         << " phase angle:" << arg(c1) << endl;
    // c1:magnitude: 5 (squred magnitude: 25)  phase angle:0.643501
          
    cout << "c2:magnitude: " << abs(c2) 
         << " (squared magnitude: " << norm(c2) << ") "
         << " phase angle: " << arg(c2) << endl;
    // c2:magnitude: 5 (squared magnitude: 25)  phase angle: 0.75
 
    cout << "c1 conjugated: " << conj(c1) << endl;
    cout << "c2 conjugated: " << conj(c2) << endl;
    // c1 conjugated: (4,-3)
    // c2 conjugated: (3.65844,-3.40819)
    
    cout << "4.4 + c1 * 1.8:" << 4.4 + c1 * 1.8 << endl;
    // 4.4 + c1 * 1.8:(11.6,5.4)

    cout << "c1 + c2: "
         << c1 + complex<double>(c2.real(), c2.imag()) << endl;
    // c1 + c2: (7.65844,6.40819)

    cout << "c1 += sqrt(c1): " << (c1 += sqrt(c1)) << endl;
    // c1 += sqrt(c1): (6.12132,3.70711)

    return 0;
}

 

posted @ 2020-06-09 15:35  ジャスミン  阅读(573)  评论(0编辑  收藏  举报