I have an assignment that is the following:
For a given integer array, find the sum of its elements and print out the final result, but to get the sum, you need to e
vector<int> v(array[0], array[10]);
This doesn't do what you want. array[0]
is the first value (1). array[10]
is in invalid access past the end of your array. To pass pointers to the vector
constructor, you want:
vector<int> v(array, array+10);
If you really want to compute the sum, std::accucumulate is what you want, not for_each
I know you were told to use for_each
, but I would actually do this - perhaps an alternative for extra credit ;-)
#include <numeric>
using namespace std;
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = accumulate(array, array + (sizeof(array) / sizeof(int)), 0);
accumulate is expressly designed for summing the elements of an iterable range.
why not just:
for_each( array, array+10, myFunction);
I'm quite sure that int*
can be used as iterator
EDIT: just checked this, it can indeed
You're not constructing the vector right. The constructor that takes two integers is
vector(size_type _Count, const Type& _Val);
So _Count is 1 and _Value is an undefined value past the end of the array.
array has indexes 0..9, so array[9] = 10
if array[10] doesnt throw an error it will contain erroneous data, causing this problem.