Boost logo

Boost Users :

From: heath_r_davis (1heathdavis_at_[hidden])
Date: 2003-04-23 14:57:13


I have experienced some difficulty with sorting lists of type:

list < shared_ptr < foo > >

Here is the expected (sorted) program output:

424238335
596516649
719885386
846930886
1189641421
1649760492
1681692777
1714636915
1804289383
1957747793

Instead, I end up with:

1804289383
846930886
1681692777
1714636915
1957747793
424238335
719885386
1649760492
596516649
1189641421

Below is the code in question:

////////////////////////////////////////////////

#include <iostream>
#include <list>
using namespace std;

#include <boost/shared_ptr.hpp>
using namespace boost;

////////////////////////////////////////////////

class my_class
{
        public:
                int m_val;
        public:
                my_class();

                bool operator<(const my_class&);
                void Display();
};

////////////////////////////////////////////////

my_class::my_class()
{
        m_val = rand();
}

bool my_class::operator<(const my_class& arg)
{
        return m_val < arg.m_val;
}

void my_class::Display()
{
        cout << m_val << "\n";
}

////////////////////////////////////////////////

int main( int argc, char **argv )
{
// list < my_class > my_list;
// list < my_class >::iterator my_iter;

        list < shared_ptr < my_class > > my_list;
        list < shared_ptr < my_class > >::iterator my_iter;

        //populate my_list
        for (int x=0; x<10; x++)
        {
// my_class tmp_obj;

                shared_ptr < my_class > tmp_obj;
                tmp_obj.reset(new my_class);

                my_list.push_back(tmp_obj);
        }

        //sort the list
        my_list.sort();

        //display contents of my_list
        my_iter = my_list.begin();
        while (my_iter != my_list.end())
        {
// (*my_iter).Display();

                (*my_iter)->Display();

                ++my_iter;
        }

        return 0;
}

////////////////////////////////////////////////

Thanks in advance for any help you may render...


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net