【问题标题】:Get iterator from pointer从指针获取迭代器
【发布时间】:2012-04-18 12:08:24
【问题描述】:

以下问题Segmentation fault executing method我停在另一个问题上。

给定:

Cluster * base;
Cluster * absorbed;

list<Cluster>::iterator li = clusters.begin();

// li is then pointed to some element.

absorbed = &(*li);   // Get a pointer to the chosen element.

base->joinCluster(absorbed);   // Perform an action with absorbed.

// li contines the cycle and now point to clusters.end()

// Now, absorbed should be deleted from list. li doesn't point to absorbed anymore.
li = & (* absorbed);
clusters.erase(li);

试图做与上述相反的操作,但 g++ 返回错误:error: no match for 'operator=' in 'li = absorbed' 我该怎么做?

我试图避免循环遍历列表中的所有元素以再次找到 absorbed 之一。

编辑:

抱歉,但我知道我错过了在absorbed = &amp;(* li); 之后li 继续循环直到clusters.end()。 因此,在循环结束时,li 不再指向absorbed。 我想我有两个选择:或者我再次循环遍历clusters 中的所有元素以找到absorbed 元素;或者我利用absorbed 指针从clusters 中删除元素。但是,我怎样才能实现第二个选项?

【问题讨论】:

    标签: c++ pointers iterator


    【解决方案1】:

    只需跳过li = &amp;(*absorbed) 行,它应该可以正常工作。

    【讨论】:

      【解决方案2】:

      您无法从T* 获得std::list&lt;T&gt;::iterator。您必须使用原始的 li 来执行迭代器操作。

      【讨论】:

        【解决方案3】:

        把它抹掉!
        如果您要删除它,则无需尝试重​​新输入值。

        【讨论】:

          【解决方案4】:

          而不是

          // Now, absorbed should be deleted from list
          li = & (* absorbed);
          clusters.erase(li);
          

          使用:

          clusters.pop_front();
          

          如果你总是处理第一个元素。

          无法从值中获取迭代器。不是原因,但相同的值可以在多个容器中或多个容器中。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-09-03
            • 2012-07-11
            • 1970-01-01
            • 1970-01-01
            • 2018-09-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多