代码之家  ›  专栏  ›  技术社区  ›  Ruggero Turra

迭代并从std::set中删除elments

  •  2
  • Ruggero Turra  · 技术社区  · 14 年前

    我有一个 std::set

    DnaSet::const_iterator next = dna_list.begin();
    DnaSet::const_iterator actual = next;
    ++next;
    
    while(next != dna_list.end()) // cycle over pairs, dna_list is the set
    {
        if (similar(*actual, *next))
        {
            Dna dna_temp(*actual);  // copy constructor
            dna_list.erase(actual); // erase the old one
            do
            {
               dna_temp.mutate(); // change dna_temp
            } while(!dna_list.insert(dna_temp).second);  // insert dna_temp
        }
        ++actual;
        ++next;
    }
    

    dna_list

    2 回复  |  直到 12 年前
        1
  •  5
  •   Peter Alexander    14 年前

    使用 actual = next 而不是 ++actual .

    actual ,它是无效的迭代器,因此 会表现得很奇怪。 next 实际的 应该有用。

        2
  •  2
  •   wilhelmtell    14 年前

    最好的选择是创建一个使用 similar()

    struct lt_different {
        bool operator()(int a, int b) {
            return a < b && !similar(a, b);
        }
    
    private:
        bool similar(int a, int b)
        {
            // TODO:when are two elements similar?
            const int EPSILON = 2;
            return abs(a - b) < EPSILON;
        }
    };
    
    // ...
    set<int> o;  // fill this set with your data
    
    // copy your data to a new set that rejects similar elements
    set<int,lt_different> s(o.begin(), o.end(), lt_different());
    

    你可以使用set s :insert elements、remove elements、modify elements——集合本身将确保集合中不存在两个类似的元素。

    std::adjacent_find() <algorithm> erase() 方法删除它们,因为它有一个需要两个迭代器的重载。