传入对 C++ 中地图的引用

发布于 2024-10-06 22:22:47 字数 759 浏览 4 评论 0原文

我希望传递对地图的引用,而不是让地图将其放置在其他地方 - 这是我正在处理的内容:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉宸 2024-10-13 22:22:47

您无法将引用存储在 STL 容器中。容器存储的是对象,而引用不是对象(另外,容器中存储的对象必须是可赋值的,而引用是不可赋值的)。

您将需要使用指针映射:

std::map<std::string, Node*>

另外,请注意所有权问题。您需要确保在所有引用它们的人都使用完这些对象之前,这些对象不会被销毁。如果您在多个位置使用了对象,请考虑使用共享所有权智能指针(例如 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:

std::map<std::string, Node*>

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文