Determining if an object is in std :: set

I am trying to determine if an object is contained within std::set. According to msdn (and other sources), the set :: find function should return end()if it does not find the element you requested.

However, when I implement code like the one below, it set::findreturns an unnecessary ( 0xbaadf00d).

set<Cell*> cellSet;

Cell* cell = new Cell();    

if (cellSet.find(cell) == cellSet.end())
{
    ...
}

Am I using this correctly? I work in Visual C ++ 2005.

+3
source share
5 answers

Your submitted code will always execute code in if, and 0xbaadf00d - the implementation marker "one end of the past."

+10
source

stl set count . , .

set<Cell*> cellSet;

Cell* cell = new Cell();    

if (cellSet.count(cell) == 0)
{
    ...
}
+5

callSet.end() 0xbaadf00d?

VS2008, , . find , .

? () ?

+1

, , , . , , , delete d.

, ++ ? . , . ( , - , , .)

0

, .

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

, Cell, Cell ( , ). ++ , , .

To actually compare objects, you need to use find_if () and pass the predicate (functor).

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.
}
0
source

Source: https://habr.com/ru/post/1707610/


All Articles