Re: Order in the STL 'set'?

From: Mike Wahler (
Date: 07/23/04

Date: Fri, 23 Jul 2004 00:56:18 GMT

"entropy123" <> wrote in message
> I'd like to use a set as a container for my user defined objects. Each
> element in the set needs to be accessed sequentially. i.e. The first
> element added to the set is always the first one I want my program to
> take a look at and then the second...and so on....

So why do you want to use a set? The purpose of a 'std::set' is
to have the elements accessible in a sorted order, and to disallow
duplicates. Wouldn't a sequence container do what you need?

> However, set
> containers arrange themselves in a code defined order.


> Is there any
> way to turn this feature off?

Not directly, but it can be defeated. Just for fun:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <ostream>
#include <set>

class C
    static int control;
    int seq;
    int member;
    C(int arg) : seq(++control), member(arg) { }

    friend bool operator<(const C& lhs, const C& rhs)
        return lhs.seq < rhs.seq;

    friend std::ostream& operator<<(std::ostream& os,
                                    const C& c)
        return os << c.member;

int C::control(0);

int main()
    std::set<C> my_set;


    std::copy(my_set.begin(), my_set.end(),
              std::ostream_iterator<C>(std::cout, "\n"));

    return 0;

But what's the point? Just use a sequence container
(e.g. vector) instead.

Also the above falls apart if the objects are serialized
and deserialized during different program invocations.