1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ complex array

  1. Mar 27, 2008 #1
    Hi, I've been trying to write a program to solve a propagation of a wave packet using the time dependent schrodinger equation.
    and I noticed I would need to use complex numbers.

    I know that I need to use #include<complex>

    I declare my array, and I started with a simple 1-d array.
    When inputting data to the array I know that I would need something like this:
    a[0] = (1,5);
    a[1] = (2,8);

    however when I output the data I only get:

    a[0] = (5,0)
    a[1] = (8,0)

    Any idea how I can get around it?

    And what about taking the complex conjugate of an array?
  2. jcsd
  3. Mar 27, 2008 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Unfortunately, it did exactly what you asked it to!

    The (default) comma operator is defined to:
    (1) Evaluate its first argument
    (2) Discard the result
    (3) Evaulate and return its second argument

    So, the expression (1, 5) correctly evaluates to 5. For example, try this statement:

    std::cout << (1, 5) << std::endl

    Your problem is that you wanted to assign a complex number into the array, and so you must create the one you want to put into the array. An example of invoking the two-argument constructor to create a complex number is the expression

    complex<double>(1, 5)

    which evaluates to the complex number 1+5i.
  4. Mar 27, 2008 #3
    Yeah, I just tried it and it did not work.

    using cout << complex<double>(1,5) does indeed output (1,5).

    However, when I use
    Code (Text):

    complex<double> a;
    a = complex<double>(1,5);
    cout << a;
    I get (5,0). And when I use std::cout << (1, 5) << std::endl I still get (5,0)
  5. Mar 27, 2008 #4


    User Avatar

    Are you sure you doing it right? It works fine here.

    Code (Text):
    #include <iostream>
    #include <complex>

    int main()
        std::cout << std::complex<double>(1.0, 5.0) << std::endl;

        a[0] = std::complex<double>(2.0, 4.0);
        a[1] = std::complex<double>(3.0, 3.0);

        std::cout << a[0] << '\n' << a[1] << std::endl;

        std::complex<double> b;
        b = std::complex<double>(4.0, 2.0);
        std::cout << b << std::endl;

        return 0;
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?