简体   繁体   English

C++ 将对象保存在列表中以便以后重用

[英]C++ Saving objects inside a list to reuse later

Suppose I own a list of edges saved inside a vector like:假设我拥有一个保存在向量中的边列表,例如:

typedef struct edge
{
  int v;
  size_t start;
  size_t end;
}e;

typedef vector<list<e>> adj_list;
adj_list tree;

I have to do logic on this tree object, but the logic is too complicated to do it in place (constricted to not recurse).我必须在这tree object 上做逻辑,但是逻辑太复杂了,无法原地做(限制为不递归)。 I need an extra data structure to handle each node.我需要一个额外的数据结构来处理每个节点。 As a simple example, lets consider incrementing each edge's v value:作为一个简单的例子,让我们考虑递增每条边的 v 值:

list<e> aux;
  aux.insert(aux.begin(), tree[0].begin(), tree[0].end());
  while (!aux.empty())
    {
      e& now = aux.front();
      aux.pop_front();
      now.v++;
      aux.insert(aux.begin(), tree[now.v].begin(), tree[now.v].end());
      
    }

The problem in doing this is that the changes made to the now variable does not reflect the value in tree .这样做的问题是对now变量所做的更改不会反映tree中的值。 I need a list(can be any list(vector,linked,queue,stack) that has an empty() boolean like Dijkstra) ds to handle my edge objects in tree .我需要一个列表(可以是任何列表(向量,链接,队列,堆栈),它有一个像 Dijkstra 一样的空()boolean) ds 来处理我在tree中的edge对象。 Is there an elegant way to do this?有没有一种优雅的方法可以做到这一点? Can I use a list of iterators?我可以使用迭代器列表吗? I'm specifically asking an "elegant" approach in hopes that it does not involve pointers.我特别要求一种“优雅”的方法,希望它不涉及指针。

As discussed in the comments, the solution is to store iterators instead of copies, eg:正如评论中所讨论的,解决方案是存储迭代器而不是副本,例如:

list<list<e>::iterator> aux;
aux.insert(aux.begin(), tree[0].begin(), tree[0].end());
while (!aux.empty())
{
  e& now = *(aux.front());
  aux.pop_front();
  now.v++;
  aux.insert(aux.begin(), tree[now.v].begin(), tree[now.v].end());    
}

This works only if you can guarantee that nothing will invalidate the stored iterators, such as certain operations on tree could do.仅当您可以保证没有任何东西会使存储的迭代器无效时,这才有效,例如tree的某些操作可以做到。

As pointed out by n.正如n 指出的那样。 'pronouns' m. '代词' m. , iterators can be considered as "generalized pointers", so many problems that regular pointers have also apply to iterators. ,迭代器可以认为是“广义指针”,所以正则指针的很多问题也适用于迭代器。

Another (slightly safer) approach would be to store std::shared_ptr s in the inner list of tree - then you can simply store another std::shared_ptr to the same object in aux which makes sure that the object cannot be accidentally deleted while it is still being referenced另一种(稍微更安全的)方法是将std::shared_ptr存储在tree的内部列表中 - 然后您可以简单地将另一个std::shared_ptr存储到aux中的同一个 object 中,以确保 object 不会被意外删除还在参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM