Choosing an STL container for storing threads

I am trying to choose the best STL container for storing Thread objects (I am writing a thread library). My problem is that I am not very familiar with any of them, and reading the api hint, I would like to consult with the one who used it before.

In any case, each object Threadhas two important attributes: _idand _priority. I need to have access to the stream using _id, so I naturally thought about hash_map. I also want the objects to be sorted using _priority(different Thread objects could have the same priority), so I was thinking of a priority queue with pointers to hash_map, but if I delete a thread that is not the first in the queue, it gets a little ugly.

Is there a better solution? Thank!

+3
source share
3 answers

To get two types of access, you need to combine the two containers ... or reuse a library that combines the containers.

Boost.MultiIndex was invented for such needs.

The section provides an example in which there are employees available by ID (unique) and sorted by name (not unique), which is pretty much what you are going to do.

Key extractors may not be obvious. Suppose your thread is ressemble:

class Thread {
public:
    std::size_t id() const;
    std::size_t priority() const;

    ...
};

You should be able to write:

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/const_mem_fun.hpp>
#include <boost/multi_index/member.hpp>

// define a multiply indexed set with indices by id and name
typedef multi_index_container<
    Thread,
    indexed_by<
        ordered_unique<
            const_mem_fun<Thread, std::size_t, &Thread::id>
        >,
        ordered_non_unique<
            const_mem_fun<Thread, std::size_t, &Thread::priority>
        >
    > 
> ThreadContainer;

Defines a stream container, uniquely identifying them id()and sorting according to them priority().

. , , , mem_fun const_mem_fun (, ).

( ) .

+4

std::map, /. _id Thread ( , ). std::vector, _priority std::sort .

0

std::unordered_map → , std::set .

0

All Articles