请问,C++ STL是否包含 二叉搜索树 (BST) 的实现,还是我需要自己构造BST对象?
如果STL中没有BST的实现,是否有其他可用的库?
我的目标是尽快地找到所需记录:我有一份记录列表(不应该超过几千个),并在其中进行每帧搜索(这是一个电脑游戏)。我使用无符号整数作为感兴趣记录的标识符。任何最快的方式都将对我最有效。
请问,C++ STL是否包含 二叉搜索树 (BST) 的实现,还是我需要自己构造BST对象?
如果STL中没有BST的实现,是否有其他可用的库?
我的目标是尽快地找到所需记录:我有一份记录列表(不应该超过几千个),并在其中进行每帧搜索(这是一个电脑游戏)。我使用无符号整数作为感兴趣记录的标识符。任何最快的方式都将对我最有效。
typedef std::map<unsigned int, record_t> my_records;
typedef std::vector< std::pair<unsigned int, record_t*> > my_records;
std::vector
通常比其他理论上具有优势的数据结构表现更好。 它的弱点在于插入/删除中间元素。 然而,在32位系统上,这将需要移动2 * 32位POD条目,您的实现可能会通过调用CPU内部函数进行内存移动来执行此操作。std::vector
,如果数量是固定的,则使用std::array
(std::tr1::array
或boost::array
)。这样,您将获得begin()
和end()
成员函数以及所有其他STL容器功能。 - sbistd::set
和 std::map
通常实现为红黑树,这是二叉搜索树的一种变体。具体细节取决于实现。
一份简洁而易懂的 CPP 二叉搜索树实现:
struct node {
int val;
node* left;
node* right;
};
node* createNewNode(int x)
{
node* nn = new node;
nn->val = x;
nn->left = nullptr;
nn->right = nullptr;
return nn;
}
void bstInsert(node* &root, int x)
{
if(root == nullptr) {
root = createNewNode(x);
return;
}
if(x < root->val)
{
if(root->left == nullptr) {
root->left = createNewNode(x);
return;
} else {
bstInsert(root->left, x);
}
}
if( x > root->val )
{
if(root->right == nullptr) {
root->right = createNewNode(x);
return;
} else {
bstInsert(root->right, x);
}
}
}
int main()
{
node* root = nullptr;
int x;
while(cin >> x) {
bstInsert(root, x);
}
return 0;
}
STL的set类通常被实现为BST。虽然没有保证(唯一确定的是它的签名,template < class Key, class Compare = less<Key>, class Allocator = allocator<Key> > class set;
),但这是一个相当安全的选择。
您的帖子说您想要速度(可能是为了更紧密的游戏循环)。
那么,为什么要浪费时间在这些慢得像糖蜜一样的O(lg n)结构上,而不是选择哈希映射实现呢?
std::unordered_map
性能和std::map
的性能! - wilhelmtell
std::map
或std::set
可能是最好的选择(如果你想存储一个键和它所指向的值,那么前者更好;如果你只关心存储键,则后者更好)。 - Argote