开发者

Quick question on Recursion and vectors

开发者 https://www.devze.com 2023-03-05 12:37 出处:网络
How would i be able to create a recurs开发者_如何转开发ive function that should accept its parameter as a vector of ints.

How would i be able to create a recurs开发者_如何转开发ive function that should accept its parameter as a vector of ints.

Pretty much i need all even numbers entered to be added while all odd numbers to be subtracted how would i do that ?


You are trying to go about solving the problem the wrong way. First, an iterative solution is far more straightforward here (and makes far more sense) than a recursive solution. However, if you do need a recursive solution, a function that takes a pair of iterators makes far more sense:

template <typename ForwardIterator>
typename std::iterator_traits<ForwardIterator>::value_type
do_math_stuff(ForwardIterator first, ForwardIterator last)
{
    if (first == last)
        return 0;

    return (*first % 2) 
        ? (*first + do_math_stuff(std::next(first), last))
        : (*first - do_math_stuff(std::next(first), last));
}

int main()
{
    std::array<int, 8> x = { 1, 2, 3, 4, 5, 6, 7, 8 };
    int result = do_math_stuff(x.begin(), x.end());
}

If you write a function that takes a whole container as an argument you have to make a brand new container for each recursive call to the function, which is just silly. By having the function take iterators into the container, you not only allow the function to be used with any forward iterable range but you also no longer require any copies of the container to be made.

Algorithms should be implemented in terms of iterators, not containers.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号