Hi everyone,

Was wondering if anyone could help...

I know the std::map automatically sorts it values - I have a map a Date object pointer, and a bool for whether it is to be used or not. But I need the dates to be in order from earliest to latest - since I need to store the object pointer, it's storing them in the wrong order now! :(

The dates are stored in YYYYMMDD format so it should be possible to order them correctly, but how would you go about sorting them? I've tried writing my own function to do it (by iterating through the map and attempting to put them in order to a new map) but the order comes out the same.

Any help would be much appreciated, even jsut a few pointers (excuse the pun :))!

std::map can take a comparator as one of its template arguments, so you just need to define you're own custom comparitor for pointers. If the thing that is pointed to has an operator< defined then you can make a one-size-fits-all template comparator:

template< typename T >
class pointer_comparator : public std::binary_function< T, T, bool >
{
public :
    bool operator()( T x, T y ) const { return *x < *y; }
};

Then you just need to pass this comparator to the map when you define it:

std::map< const date*, bool, pointer_comparator< const date* > > my_pointer_map;

Easy as that :)

Here's a toy example with int pointers:

#include <iostream>
#include <map>
#include <functional>

template< typename T >
class pointer_comparator : public std::binary_function< T, T, bool >
{
public :
    bool operator()( T x, T y ) const { return *x < *y; }
};

int main()
{
    typedef std::map< const int*, bool, pointer_comparator< const int* > > map_t;
    map_t my_map;

    int* a = new int(2);
    int* b = new int(1);

    my_map[a] = false;
    my_map[b] = true;

    for ( map_t::const_iterator it = my_map.begin(); it != my_map.end(); ++it )
        std::cout << *(it->first) << " " << ( it->second ? "true" : "false" ) << std::endl;

    delete a;
    delete b;

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.