简体   繁体   中英

Vector slicing in C++ in recursion

Here is a simple function to print a list in reverse using python.

def print_list(lst):
    if not lst:
        return
    print_list(lst[1:])  # How to achieve this slicing in C++ vector without any global, static variable.
    print(lst[0], end=" ")

I have to rewrite this function in C++ without modifying the function prototype as well as I don't want to use the static/global index variables.

C++ function prototype and Pseudocode.

void print_rev(vector<int> &vec) {
    if(it reaches vector end)
        return;
    print_rev(vec[1:])
    print(vector elements during stack unwinding phase)
} 

How to slice the vector like in the python function?

I have to rewrite this function in C++ without modifying the function prototype as well as I don't want to use the static/global index variables.

If the sole purpose of the function is to write it in reverse, you can use std::vector::reverse_iterator . You don't need modify the input object or create temporary ones in a recursive call.

void print_rev(vector<int> &vec)
{
    for ( auto iter = vec.rbegin(); iter != vec.rend(); ++iter )
    {
        print(*iter);
    }
} 

Personally I would not use recursion to do this and use a reverse iterator instead like in the answer given by @r-sahu. However, if you really want to do it using recursion then it is possible with another overload of print_rev() that takes iterators. This would avoid having to create a new temporary vector with each call of print_rev() :

#include <vector>
#include <iostream>

using Iter = std::vector<int>::iterator;

void print_rev(Iter start, Iter end)
{
    if (start == end)
        return;
    print_rev(std::next(start), end);
    std::cout << *start;
}

void print_rev(std::vector<int> &vec) {
    print_rev(vec.begin(), vec.end());
}

int main() {
    std::vector<int> v = {1,2,3,4,5};
    print_rev(v);   
}

Output:

54321

Here's a demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM