【问题标题】:keeping an iterator valid while splicing a list C++在拼接列表 C++ 时保持迭代器有效
【发布时间】:2018-12-19 01:43:55
【问题描述】:

有一些关于迭代器的帖子,列表 here 使用 insertsplice here 函数,但我仍然无法根据我的情况翻译它们,我正在遍历一个列表,如果条件满足我想将元素拼接(移动)到另一个列表,但正如here 所述,迭代器跳转到拼接容器。如何保持迭代器与原始循环相关,如下例所示。

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <ctime>
#include <list>

using namespace std;

class Individual {
  public:
    Individual(bool state) : state_(state) {}
    bool my_state(void) {
        return state_;
    }
  private:
    bool state_ = true;
};


int main () {
    cout << "----------Enter Main----------" << endl;
    list<Individual>  list_individuals;
    list<Individual>  cache_list_individuals; 

    // initialise
    for (auto i = 0; i < 100; ++i) {
        if (i <= 50)
            list_individuals.push_back(new Individual(true));
        else
            list_individuals.push_back(new Individual(false));
    }
    unsigned counter = 0;
    for (auto iter = list_individuals.begin(); iter != list_individuals.end(); ++iter, ++counter) {
        if ((*iter).my_state()) {
            cache_list_individuals.splice(cache_list_individuals.begin(),list_individuals, iter);
            // I need to make the iterator related to list_individuals not cache_list_individuals
        }
    }

    cout << "----------Exit Main----------" << endl;
    system("PAUSE");
    return 0;
}

【问题讨论】:

  • 在拼接之前获取下一个迭代器(仍然指向第一个列表)。
  • 最容易做到的是将第二个 for 更改为 while 声明第二个 iter_tmp 并使用 std::advancestd::next (C++11) 并分配 @ 987654332@ 在iter 上调用advancenext 并使用iter_tmpsplice
  • 迭代器指向元素。你移动一个元素,迭代器随之移动。如果你想要一个不移动的迭代器,让它指向一个不移动的元素。

标签: c++ iterator splice


【解决方案1】:
for (iter = list.begin(); iter != list.end();) {
    otherIter = iter++;
    if (condition) {
        otherList.splice(otherList.cend(), otherIter, list);
    }
}

将递增迭代器移动到循环中。 使用后自增,移动 iter,并保持它遍历 list,而 otherIter 在 splice() 之后遍历 otherList。

【讨论】:

    【解决方案2】:

    使用循环迭代器的副本进行拼接:

    if ((*iter).my_state()) {
        auto splice_iter = iter;
        cache_list_individuals.splice(cache_list_individuals.begin(), list_individuals, splice_iter);
    }
    

    编辑:反对票是合理的。复制后,两个迭代器都将指向 cache_list_individuals 列表中移动的元素。 David C. Rankin 上面的评论是我的代码试图去的地方。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-07
      • 2015-02-18
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 2012-05-09
      • 2016-03-15
      • 2012-10-11
      相关资源
      最近更新 更多