Boost logo

Boost :

Subject: Re: [boost] std::map<> - like structure for other than std::pair<>?
From: M.A. van den Berg (thijs_at_[hidden])
Date: 2015-04-14 07:37:28


On 14 Apr 2015, at 13:26, David Hagood <david.hagood_at_[hidden]> wrote:

> Several times I have run into a use case where I have some object that I would like to access via something like a std::map<>, but which already contains a member that I would like to use as a key. Is there any data structure that "acts like a map", but instead of storing std::pair<key,value> allows me to store an object directly, and specify what member of that object is the key value?
>
> I can give a specific use case for this:
>
> For those of you not familiar with the SCA, there is an object called CF::Properties. This is a CORBA sequence (think std::vector) of objects of {string name, CORBA::Any value}, used to store metadata. Ideally, I'd like to have an object that I could initialize from that sequence that would allow me to do things like this:
>
> inline string &getKey(CF::Property &x)
> {
> return x.name;
> }
>
> void foo(CF::Properties &meta)
> {
> mapLikeThing<CF::Property,getKey> myMap(meta);
> double sampleRate;
> myMap["SampleRate"] >> sampleRate;
> setHardwareSampleRate(sampleRate);
> }
>

You can store your objects in a std::set instead of a map and then provide a custom compare function that compared your objects given your key in them. E.g.

struct my_compare {
    bool operator() (const MyObj& lhs, const MyObj& rhs) const{
        return lhs.name < rhs.name;
    }
};

std::set<MyObj, my_compare> s;


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk