传入对 C++ 中地图的引用
我希望传递对地图的引用,而不是让地图将其放置在其他地方 - 这是我正在处理的内容:
map<string, Node> _neighbors; // Instance Variable
Node& neighbor(Node& neighbor) {
cout << "HOST: "<< neighbor.host() << " ADDRESS: " << &neighbor << endl;
string key = this->getKey(neighbor);
if(!_neighbors.count(key)) {
_neighbors[key] = neighbor;
cout << "HOST (AFTER): "<< _neighbors[key].host() << " ADDRESS: " << &_neighbors[key] << endl;
neighbor.neighbor(*this);
}
return *this;
}
输出: 当我调用 n1.neighbor(n2); 时// n1 是一个 host=1 的节点,n2 是一个 host=2 的节点
HOST: 2 ADDRESS: 0x7fff5fbfe580
HOST (AFTER): 2 ADDRESS: 0x100100128
I'm looking to pass in a reference to a map and NOT have map place it somewhere else - Here's what I'm working with:
map<string, Node> _neighbors; // Instance Variable
Node& neighbor(Node& neighbor) {
cout << "HOST: "<< neighbor.host() << " ADDRESS: " << &neighbor << endl;
string key = this->getKey(neighbor);
if(!_neighbors.count(key)) {
_neighbors[key] = neighbor;
cout << "HOST (AFTER): "<< _neighbors[key].host() << " ADDRESS: " << &_neighbors[key] << endl;
neighbor.neighbor(*this);
}
return *this;
}
Output:
When I call n1.neighbor(n2); // n1 is a Node with host=1 and n2 is a Node with host=2
HOST: 2 ADDRESS: 0x7fff5fbfe580
HOST (AFTER): 2 ADDRESS: 0x100100128
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法将引用存储在 STL 容器中。容器存储的是对象,而引用不是对象(另外,容器中存储的对象必须是可赋值的,而引用是不可赋值的)。
您将需要使用指针映射:
另外,请注意所有权问题。您需要确保在所有引用它们的人都使用完这些对象之前,这些对象不会被销毁。如果您在多个位置使用了对象,请考虑使用共享所有权智能指针(例如
shared_ptr
)来为您管理对象生命周期。 C++ 中的手动资源管理充满危险,应不惜一切代价避免。You can't store references in an STL container. Containers store objects and references are not objects (in addition, the objects stored in a container must be assignable, and references are not assignable).
You'll want to use a map of pointers:
Also, beware of ownership issues. You need to make sure that the objects are not destroyed until everyone that has a reference to them is done using them. If you have objects used in multiple places, consider using a shared ownership smart pointer, like
shared_ptr
, to manage object lifetimes for you. Manual resource management in C++ is fraught with peril and should be avoided at all costs.