begin() vs rbegin(): how can I avoid duplication? Can the display function be re-written to avoid duplication of the std::for_each loop?

#include &lt;iostream&gt;
#include &lt;set&gt;
#include &lt;algorithm&gt;

struct Widget
{
    int id;
    Widget(int i) : id(i){}
};

namespace std
{
    template&lt;&gt;
    struct less&lt;Widget *&gt; {
    public:
        bool operator ()(Widget *const&amp; a, Widget *const&amp; b) const {
            return  (a-&gt;id &lt; b-&gt;id);
        }
    };
}

void display(const std::set&lt;Widget *&gt;&amp; wList, bool order)
{
    if (order) {
        std::for_each(wList.begin(), wList.end(), [](const Widget* x) {
            std::cout &lt;&lt; x-&gt;id &lt;&lt; std::endl;
        });
    }
    else {
        std::for_each(wList.rbegin(), wList.rend(), [](const Widget* x) {
            std::cout &lt;&lt; x-&gt;id &lt;&lt; std::endl;
        });
    }
}

int main()
{

    std::set&lt;Widget *&gt; s;

    s.insert(new Widget(1));
    s.insert(new Widget(2));
    s.insert(new Widget(5));
    s.insert(new Widget(3));
    s.insert(new Widget(9));
    s.insert(new Widget(7));

    display(s, false);
}
I would re-write the display to take iterators.

template&lt;typename I&gt;
void display(I begin, I end)
{
    std::for_each(begin, end, [](const Widget* x) {
         std::cout &lt;&lt; x-&gt;id &lt;&lt; std::endl;
    });
}


Then you can pass any container that contains Widget pointers to the method. Also solves the problem about ordering. You pass the appropriate iterators for the task.

But my main problem. Is why are you storing pointers in a container?
Who owns the pointers? If it is the container then you are doing it wrong as the destructor will not clean up (nor will replacing elements do the correct thing). For this you should use boost::ptr_set (in &lt;boost/ptr_container/ptr_set_adapter.hpp&gt;) or std::set&lt;std::unique_ptr&lt;Widget&gt;&gt; if the container is not taking ownership then it should hold references to the object std::set&lt;std::ref&lt;Widget&gt;&gt; there are other alternatives but it depends intirely on the semantics you intend to achieve.

But pointers in containers is a no-no (in general). Better have a darn good reason.