-7

I have two inputs(real and imaginary parts) for n complex numbers. I can't figure out how to store them together in a vector such that i can perform complex calculations with STL complex functions. This is something I tried but Time Limit gets exceeded.

vector<complex<double> > a;
for(i=0;i<d;i++)
{
    int temp;
    cin>>temp;
    real.push_back(temp);
}
for(i=0;i<d;i++)
{
    int temp;
    cin>>temp;
    imag.push_back(temp);
}
for(i=0;i<d;i++)
{
    a.push_back(complex<double>(real[i], imag[i]));
}
  • Please show us what have you tried, and explain what doesn't work with your solution. – Algirdas Preidžius Aug 24 '18 at 13:37
  • 1
    std::vector is the type you want – Neil Gatenby Aug 24 '18 at 13:39
  • 2
    [`std::vector>`?](https://en.cppreference.com/w/cpp/numeric/complex) – BoBTFish Aug 24 '18 at 13:39
  • It seem the real problem isn't that you don't know what library component to use, but that "Time Limit gets exceeded". Please give a full explanation of what your code is trying to do, and a [mcve] - then we may be able to suggest a more efficient solution. – BoBTFish Aug 24 '18 at 13:41
  • there is no obvious reason why this should trigger a time-limit exceeded. My first guess is that the `cin >>` call takes more time then all the rest. I suspect that you exceed the limit somewhere else in code that you dont show here (I doubt that there is a challenge "fill a vector of complex numbers as fast as you can", usually they require you to do also some output ;) – 463035818_is_not_an_ai Aug 24 '18 at 13:55
  • just another wild guess: if you try to read more input than is provided, then the `cin >> temp;` will block forever (or until you exceed the time limit, whatever happens first) – 463035818_is_not_an_ai Aug 24 '18 at 13:57

1 Answers1

1

Here's an example I used:

double real;
double imaginary;
std::vector<std::complex<double> > database;
//...
std::cin >> real;
std::cin >> imaginary;
const std::complex<double> temp(real, imaginary);
database.push_back(temp);

In the above example, I read in the real and imaginary components separately. Next, I create a temporary complex object using the real and imaginary components. Finally, I push_back the value to the database.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154