I’m new to c++ and programming in general. Feel free to leave any hints, tips, or suggestions about my code!!
I am trying to copy my doubles from a vector to an array. I used copy() and it is copying all the elements except for the last. So the last element in the array stays exactly the same as it was before I used copy. So when I try to add the sums of the elements in the array, I don’t get the correct sum.
Here is my code:
vector<double> myVector;
double myArray[4];
double myDouble = 0.0;
...//(add elements to vector)
copy(&myVector[0], &myVector[4], myArray);
for(int i = 0; i < 4; i++)
{
myDouble += myArray[i];
if(i == 4)
cout << "The sum of your values is " << fixed << setprecision(2) << myDouble << endl;
}
Thank you! Let me know if I need to be more specific.
The call to
std::copy()copies four elements. This seems to fill your array. Note that your array contains exactly 4 elements and the last valid index is3. Your vectormyVectorseems to include at least 5 elements: If it contains less then 5 elements, the expressionmyVector[4]is illegal. That said, the end iterator in a sequence always refers to the element behind the last value of the sequence, i.e., sequences are half-open: the begin is included, the end is the first element not included.That said, you probably want to copy like this:
Of course, to get the sum of the elements in the vector you would actually use