c++ for_each() and object functions

2020-03-26 05:19发布

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?

标签: c++
10条回答
\"骚年 ilove
2楼-- · 2020-03-26 05:19

If you really want to compute the sum, std::accucumulate is what you want, not for_each

查看更多
孤傲高冷的网名
3楼-- · 2020-03-26 05:22

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].

查看更多
唯我独甜
4楼-- · 2020-03-26 05:23
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);
查看更多
ら.Afraid
5楼-- · 2020-03-26 05:24

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.

查看更多
闹够了就滚
6楼-- · 2020-03-26 05:26

The array has 10 elements so 10 is not a valid array index.

vector<int> v(array[0], array[10]);
                              ^^

What you want is:

vector<int> v(array, array + sizeof(array) / sizeof(int) );
查看更多
霸刀☆藐视天下
7楼-- · 2020-03-26 05:29

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

查看更多
登录 后发表回答