Search code examples
c++complex-numbersstdcomplex

How can I store an array of complex numbers?


I want to write code that takes a sequence of complex numbers and searches for a number in it. But I don't know how to write a function to form the sequence. This is what I've tried so far:

class complex { 
private:
    int real;
    int image; 
    int n;
    int *a;
    
public:
    complex(float l, float k) : real(l), image(k) {}
        
    float set(float l, float k)
    {
        cout << "enter size of array: ";
        cin >> n;
        for (int i = 0; i < n; i++)
        {
            cout << "enter real part: ";
            cin >> l;
            cout << "enter image part: ";
            cin >> k;
            *(a+i) = complex(l, k);
        }
    }
};

Solution

  • Because you arent allowed to use the library (which is stupid), what I would suggest is creating a struct to save the data

    struct complexNum {             
      int real;        
      int imaginary;   
    };
    

    The other problem is that a is undefined as is and why not just use a[i]. Also instead why not create a typical array? You also dont need arguments or a return type for your function.

    Something like:

    class complex{  
        private:
            struct complexNum {             
                int real;        
                int imaginary;   
            };
            int n;
            complexNum* a;
        
        public:        
            void set()
            {
                cout<<"enter size of array: ";
                cin>>n;
                a = new complexNum[n];
                for (int i=0; i<n; i++)
                {
                    complexNum num;
                    cout<<"enter real part: ";
                    cin>>num.real;
                    cout<<"enter image part: ";
                    cin>>num.imaginary;
                    a[i]=num;
                }
            }
    };