Search code examples
c++recursionstdset

How to print a set in reverse order recursively in C++?


I've tried the following code to print an std::set<int> in reverse order:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <list>
#include <map>
#include <utility>
#include <set>
#include <stack>

using namespace std;

void setRecursivePrinting(set<int> s, set<int>::iterator it)
{
    int x;
    x = *it;
    it++;
    if (it != s.end())
    {
        setRecursivePrinting(s, it);
    }
    cout << x << '\t';
}

int main()
{
    set<int> s;
    s.insert(44);
    s.insert(2);
    s.insert(10);
    s.insert(8);
    s.insert(100);
    setRecursivePrinting(s, s.begin());
    
    return 0;
}

But the problem is the output doesn't show anything. Am I missing something? I'm aware about the rbegin() and rend() functions too, but I just want to learn to implement it in a recursive way.


Solution

  • I think you need to be passing the set by reference and not by value.