Ordering output of C++ std::set

1.8k views Asked by At

I want to list the output of my set in alphabetical order. Below is an attempt at getting to this, but it seems slow / inefficient and I haven't even finished it yet.

void ordered(ostream &os) {
    bool inserted = false;
    for (objects::iterator i = begin(); i != end(); ) {
        for (objects::iterator x = begin(); x != end(); ++x) {
            if((**i) < (**x)) { //overloaded and works
                os << **i << endl;
                inserted = true;
                break;
            }
        }
        if(inserted) {
            ++i;
        }
    }
}

Clearly this will only output objects that come after the first object alphabetically.

I also considered moving the objects from a set into another container but it still seems inefficient.

2

There are 2 answers

0
mcserep On

The std::set is an ordered container, see reference:
http://en.cppreference.com/w/cpp/container/set

std::set is an associative container that contains a sorted set of unique objects of type Key. Sorting is done using the key comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Sets are usually implemented as red-black trees.

0
Cameron On

std::set is already ordered. It looks like you merely need to use a custom comparer that compares the pointed-to values instead of the pointers themselves (which is the default):

template<typename T> struct pless {
    inline bool operator()(const T* a, const T* b) const { return *a < *b; }
};
std::set<Foo*, pless<Foo> > objects;