Nếu số mục nằm trong hàng trăm mục, bạn có thể sử dụng tìm kiếm tuần tự đơn giản. Thuật toán này được tích hợp vào C++ như find()
chức năng:
#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);
}
Hãy chắc chắn rằng Cell
đã operator<
ghi đè.
Nếu danh sách là rất lớn, bạn có thể muốn sử dụng tìm kiếm nhị phân, mà cũng đi kèm với 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);
}
Nguồn
2010-04-20 05:48:38
Bạn có thể chấp nhận câu trả lời cho các câu hỏi trước đó của bạn bằng cách đánh dấu các dấu kiểm bên cạnh trái của câu trả lời – Amsakanna
Hah, cảm ơn bạn, không bao giờ nhận ra. :) – Befall