c++ for_each() and object functions

前端 未结 10 812
盖世英雄少女心
盖世英雄少女心 2021-01-14 05:31

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

相关标签:
10条回答
  • 2021-01-14 05:43
    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);
    
    0 讨论(0)
  • 2021-01-14 05:43

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

    0 讨论(0)
  • 2021-01-14 05:44

    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.

    0 讨论(0)
  • 2021-01-14 05:49

    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

    0 讨论(0)
  • 2021-01-14 05:49

    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.

    0 讨论(0)
  • 2021-01-14 05:52

    array has indexes 0..9, so array[9] = 10

    if array[10] doesnt throw an error it will contain erroneous data, causing this problem.

    0 讨论(0)
提交回复
热议问题