我正在用C++编写一个搜索算法,我需要做的事情之一是有几条if语句来检查上面,下面,左边和右边的单元格。简单的方法来检查项目是否在列表中?
每次发现一个单元格打开并添加到堆栈中时,我希望它将其添加到已检查过的单元格列表中。我想在if语句中说if(thisCell is not in checkedCells)
。
任何简单的想法?
谢谢!
我正在用C++编写一个搜索算法,我需要做的事情之一是有几条if语句来检查上面,下面,左边和右边的单元格。简单的方法来检查项目是否在列表中?
每次发现一个单元格打开并添加到堆栈中时,我希望它将其添加到已检查过的单元格列表中。我想在if语句中说if(thisCell is not in checkedCells)
。
任何简单的想法?
谢谢!
如果项目的数量是几百,您可以使用简单的顺序搜索。该算法是内置到C++作为find()
功能:
#include <algorithm> // for find()
typedef std::vector<Cell> CellList;
CellList checked_cells;
// .....
Cell cellToSearch;
if (is_in_checked_cells (cellToSearch, cells))
{
// .....
}
// Makes a sequential search using find().
static bool
is_in_checked_cells (const Cell &cell, const CellList &cells)
{
CellList::const_iterator end = cells.end();
CellList::const_iterator item = std::find (cells.begin(), end, cell);
return (item != end);
}
确保Cell
已operator<
覆盖。
如果该列表是非常大的,你可能需要使用二进制搜索,其中还带有C++捆绑:
#include <algorithm> // for sort() and binary_search()
CellList checked_cells;
// Make sure the cells are sorted.
checked_cells.sort (checked_cells.begin(), checked_cells.end());
Cell cellToSearch;
if (is_in_checked_cells (cellToSearch, cells))
{
// .....
}
// Searches using binary_search().
static bool
is_in_checked_cells (const Cell &cell, const CellList &cells)
{
return std::binary_search (cells.begin(), cells.end(), cell);
}
您可以通过标记勾选答案左侧下一步接受以前的问题的答案 – Amsakanna 2010-04-20 04:48:11
哈,谢谢,从来没有意识到。 :) – Befall 2010-04-20 04:51:44