C++ 如何能够对象是否有一个指向其在 std::list 中位置的迭代器作为成员?

发布于 2024-10-15 01:58:35 字数 475 浏览 6 评论 0原文

我有一个应用程序,其中有相互连接的节点。每个节点都存储到其他节点的传入和传出连接的列表。有时,接收节点需要能够摆脱其传入连接之一。发生这种情况时,我希望该连接不仅从接收节点的传入连接列表中删除,而且还从发送节点的传出连接列表中删除。但为了做到这一点,接收节点需要发送节点的迭代器来进行连接。如果我可以将该迭代器存储为连接对象的成员,那就太好了。但尝试这样做甚至无法编译。当我尝试将迭代器声明为类成员时,编译器告诉我它是未定义的类型。这就是我的类声明的样子:

class Connection
{
   public:
   Connection();
   ~Connection();

   Node* pSourceNode;
   std::list<Connection*>::iterator SourcesIterator;
};

有没有什么巧妙的方法可以使这个或类似的东西工作而不必编写我自己的链表?也许到目前为止我还没有了解一些数据结构?

I have an application where I have nodes that have connections to eachother. Each node stores a list of incoming and outgoing connections to the other nodes. From time to time the receiving node needs to be able to get rid of one of its incoming connections. When this happens, I want the connection to be removed from not only the receiving node's list of incoming connections, but also from the sending node's list of outgoing connections. But in order to do this, the receiving node needs the sending node's iterator for the connection. It would be nice if I could just store that iterator as a member of the connection object. But trying to do this will not even compile. When I try to declare an iterator as a class member, the compiler tells me that it is an undefined type. This is what my class declaration looks like:

class Connection
{
   public:
   Connection();
   ~Connection();

   Node* pSourceNode;
   std::list<Connection*>::iterator SourcesIterator;
};

Is there any neat way to make this or something like it work without having to write my own linked list? Perhaps some data structure that has thus far eluded me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

魔法唧唧 2024-10-22 01:58:35

我能够很好地编译你的代码。您是否在标题中执行 #include

无论如何,您可能不希望保留迭代器;大量操作会使它们失效。您可以保留指向相关列表的指针,并在需要时获取新的迭代器

I was able to compile your code just fine. Are you doing a #include <list> in the header?

You may not wish to keep around the iterator anyway; a large number of operations invalidate them. You could keep a pointer to the list in question and get a new iterator when needed.

薄情伤 2024-10-22 01:58:35

您可以尝试使用 typedef/forward 声明组合,在 VC6 中可能效果更好:

typedef class Connection* ConnectionPtr;
class Connection
{
   public:
   Connection();
   ~Connection();

   Node* pSourceNode;
   std::list<ConnectionPtr>::iterator SourcesIterator;
};

You might try a typedef/forward declaration combination, might work better in VC6:

typedef class Connection* ConnectionPtr;
class Connection
{
   public:
   Connection();
   ~Connection();

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