开发者

Can a std::map value object contain a reference to the corresponding key?

Essentially, what I'd like is for the value object to maintain a reference to the corresponding key object, because there's some useful information in there, which would be nice to access via the value object.

What I'm attempting to do may just not make sense, but consider the following:

class key
{
    // ... Various members ...
    friend bool operator< (const key &lhs, const key &rhs) { /* ... */ }
};

class value
{
public:
    value(const key &k) : k(k) {}
private:
     const key &k;
    // ... Various members ...

};


std::map<key,value> m;

// start a new scope, which may be due to e.g. function call, loop, etc.
{
    key k;  // I'm on the stack!

    m.insert(std::pair<key,value>(k, value(k)));
}

Of course, this doesn't w开发者_如何学Pythonork, because this is a reference to a stack object, which breaks as soon as k goes out of scope. Is there somehow a way to get a reference back to the copy of the key maintained in the map?


You could put the reference in place after insertion, but you'd have to make it a pointer:

std::map<key, value>::iterator iter = m.insert(std::make_pair(k, v)).first;
iter->second.setValue(&iter->first);


Why not reference the member of value as your key?

class key { friend bool operator< (const key &,const key&); }
class value {
    public:
       value(const key &k) : k(k) {}
       const key &key() const {return k};
    private:
       key k;
}

std::map<key,value> m;
key k;
value v(k);
m.insert(std::pair<key,value>(v.key(),v));

... or somesuch. It seems like constructing the key inside the value object would generally be easier.

More like:

#include <map>
#include <iostream>

struct key {
    key(unsigned int ik) : k(ik) {}
    unsigned int k;
    friend bool operator< (const key &,const key &);
};
bool operator<  (const key &me,const key &other) {return me.k < other.k;}

struct value {
    value(unsigned int ik, unsigned int iv) : k(ik), v(iv) {}
    const key &theKey() const {return k;}
    unsigned int v;
    key k;
};

int main() {
    std::map<key,value> m;
    value v(1,3);
    m.insert(std::pair<key,value>(v.theKey(),v));

    for(std::map<key,value>::iterator it=m.begin(); it!=m.end();++it)
        std::cout << it->second.theKey().k << " " << it->second.v << "\n";
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜