I am trying to port the following JavaScript code to C++:
var vector = new array();
for (var i = 0; i < points.length; i++)
{
var newX = points[i].X * cos - points[i].Y * sin;
var newY = points[i].Y * cos + points[i].X * sin;
vector[vector.length] = newX;
vector[vector.length] = newY;
sum += newX * newX + newY * newY;
}
I can’t seem to understand what is happening in these lines:
vector[vector.length] = newX;
vector[vector.length] = newY;
What purpose does it serve to overwrite the value at the same location in the array?
JavaScript arrays dynamically expand to hold new elements, so to append new items you need only assign to the next available index.
Array indexes are zero-based, so given an array called “vector”,
vector.lengthis one past the last element. Nothing is being over-written; The linevector[vector.length] = xappendsxto the end of the array.In JavaScript, the following methods of appending elements are identical, though using
pushmore clearly indicates your intent:The equivalent C++ code (assuming you’re using
std::vector) would