基本上,我想要的是value
对象维护对相应key
对象的引用,因为那里有一些有用的信息,通过{访问是很好的{1}}对象。
我试图做的事情可能没有意义,但请考虑以下因素:
value
当然,这不起作用,因为这是对堆栈对象的引用,只要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)));
}
超出范围就会中断。是否有某种方法可以将引用返回到k
中维护的密钥副本?
答案 0 :(得分:1)
为什么不引用值的成员作为您的密钥?
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));
......或者其他一些人。似乎在值对象中构造键通常会更容易。
更像是:
#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;
}
答案 1 :(得分:1)
您可以在插入后将引用放置到位,但您必须将其作为指针:
std::map<key, value>::iterator iter = m.insert(std::make_pair(k, v)).first;
iter->second.setValue(&iter->first);