代码之家  ›  专栏  ›  技术社区  ›  Kevin Laity

确定对象是否在std::set中

  •  3
  • Kevin Laity  · 技术社区  · 17 年前

    std::set end() 如果它找不到你要的元素。

    set::find 退回垃圾( 0xbaadf00d

    set<Cell*> cellSet;
    
    Cell* cell = new Cell();    
    
    if (cellSet.find(cell) == cellSet.end())
    {
        ...
    }
    

    5 回复  |  直到 17 年前
        1
  •  10
  •   David Schmitt    17 年前

    您发布的代码将始终执行 if ,以及 0xbaadf00d

        2
  •  5
  •   Alex B    17 年前

    count

    set<Cell*> cellSet;
    
    Cell* cell = new Cell();    
    
    if (cellSet.count(cell) == 0)
    {
        ...
    }
    
        3
  •  1
  •   JaredPar    17 年前

    callSet.end()的值是否也为0xbaadf00d?

    我在VS2008中运行了这个示例代码,一切都按预期运行。find函数返回了一个指向原始值的迭代器。

        4
  •  0
  •   j_random_hacker    17 年前

    仅仅 您提供的代码片段,我保证您会发现它执行时没有问题。这个问题几乎可以肯定是由于程序中其他地方发生的内存分配错误造成的,例如引用未初始化的指针或指向已被初始化的对象的指针 delete

    你熟悉C++容器如何管理它们的对象吗?他们不会为你删除指针。在可能的情况下,使用对象容器而不是指向对象的指针总是更安全的。(有时需要指针容器,特别是当您希望容器存储来自单个类层次结构的不同类型的对象时。)

        5
  •  0
  •   Loki Astari    17 年前

    一个简单的错误是,你应该测试不等于结束。

    set<Cell*> cellSet;
    Cell* cell = new Cell();
    if (cellSet.find(cell) != cellSet.end())     // Test NOT EQUAL to end
    {
         // Found item in set.
    }
    

    但您也应该注意,您不是在比较实际的Cell值,而是在比较指向Cell对象的指针(这可能是您想要的,也可能不是)。通常在C++中,你不倾向于将指针存储在容器中,因为指针没有隐含的所有权,但有时这是可以的。

    struct PointerCellTest
    {
        Cell&  m_lhs;
        PointerCellTest(Cell* lhs): m_lhs(lhs) {}
        bool operator()(Cell* rhs)
        {
             return lhs.<PLOP> == rhs.<PLOP>
        }
    };
    
    
    if(find_if(cellSet.begin(),cellSet.end(),PointerCellTest(cell)) != cellSet.end())
    {
         // Found item in set.
    }