Reputation: 435
In C, I am able to use complex numbers inside of an expression using CMPLX
:
#include <complex.h>
int main(){
double _Complex result;
//complicated code
result = ((3.1*CMPLX(0.,1.))+2.);
return 0;
}
How do I do the same in C++?
#include <complex>
int main(){
std::complex<double> result;
//complicated code
result = ((3.1*???(0.,1.))+2.); // what to put in '???'
return 0;
}
Is there something short I can put in for ???
? I don't want to write it with a +
operation: 0.0 + 1.0 I
.
Upvotes: 0
Views: 520
Reputation: 48615
You can create a type alias to make the std::complex
type easier to use.
For example:
#include <complex>
#include <iostream>
// create a type alias
using CMPLX = std::complex<double>;
int main()
{
// use it the same way you did in `C`
auto result = ((3.1 * CMPLX(0.0, 1.0)) + 2.0);
std::cout << "result: " << result << '\n';
}
Output:
result: (2,3.1)
Upvotes: 1
Reputation: 21131
The simplest would be to use user defined literals to create a complex
literal
#include<complex>
using namespace std::literals;
auto result = (3.1 * 1if) + 2;
Or if you don't have C++14, calling the constructor of a class will create a temporary
auto result = (3.1 * std::complex<double>{0, 1}) + 2;
Upvotes: 2