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 execute the function for_each() in STL only once (without a loop).
As of now this is my code:
void myFunction (int i) {
cout << " " << i << " " << endl;
}
int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
vector<int> v(array[0], array[10]);
for_each( v.begin(), v.end(), myFunction);
return 0;
}
But for some reason the output shows up as 4198853, at first I thought it was a memory address but I figured out that was wrong. Any idea's as to what I might be doing wrong?
If you really want to compute the sum, std::accucumulate is what you want, not for_each
You need to take the address of array[0] and array[sizeof(array) / sizeof(*array)]. Vector constructor takes iterator types (i.e. pointers in this context), it can't magically determine the value of array[1] from the value of array[0].
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 thevector
constructor, you want: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.
The array has
10
elements so10
is not a valid array index.What you want is:
why not just:
I'm quite sure that
int*
can be used as iteratorEDIT: just checked this, it can indeed