1

I am trying to assign part of a QVector double array to complex double array in Qt.

Running the following code, I have the problem that std::cout << y.at(i) << std::endl; correctly prints a 16-bit integer value but std::cout << y1[i] << std::endl; prints zeros: (0,0) (0,0) (0,0) ...

I would like the result (y[0],0) (y[1],0) (y[2],0)...

Please can someone advise what is wrong?

QVector<double> x(100), y(100);  // Original QVector

std::complex<double> y1[100];
int i=0;

while(i<101)
{  
   // get y values from somewhere else (quint8 data8)

   y[i] = (256.0*data8[2*i]) + 1.0*data8[2*i+1];
   std::cout << y.at(i) << std::endl;

   y1[i] = (y.at(i),0.0);
   std::cout << y1[i] << std::endl;

   i++;
}
Sergey
  • 7,985
  • 4
  • 48
  • 80
Michael T
  • 21
  • 3

1 Answers1

1

Let's look at this expression:

(y.at(i), 0.0)

In C++ parentheses are just a grouping technique, which is used for operator precedence designation. For example, if you execute 2*2+2, you'll get six. But if you want to get eight, you need parentheses: 2*(2+2). So you assignment line is equivalent to:

y1[i] = y.at(i), 0.0;

Why does it compile and what does it mean? It compiles because a comma operator is used. In C++, comma is a binary operator with a very simple action: it computes it's left-hand argument, throws the result away, then computes it's right-hand argument and returns the result. So in your case it discarded y.at(i) and returned zero, which was successfully assigned to y1[i]. The shortest way to do what you want in modern C++ is to use initializer lists:

y1[i] = {y.at(i),0.0};

If you have an ancient compiler, it's just a bit more verbose:

y1[i] = std::complex<double>(y.at(i), 0.0);
Community
  • 1
  • 1
Sergey
  • 7,985
  • 4
  • 48
  • 80
  • OK, silly mistake. Thank you for the thorough explanation as I was not familiar with that syntax, or the comma operator. I hope this is useful for other Qt / C++ newcomers to learn from. – Michael T Nov 16 '16 at 12:37
  • @MichaelT If the answer is helpful for you, consider accepting it – demonplus Nov 16 '16 at 16:56