B树是一种多路搜索树,常用于数据库和文件系统等场景中。以下是一个简单的C++实现B树的示例:
#include <iostream>
#include <vector>
// B树节点
template<typename T>
class BTreeNode {
public:
bool leaf; // 是否为叶子节点
std::vector<T> keys; // 键值列表
std::vector<BTreeNode<T>*> children; // 子节点列表
// 构造函数
BTreeNode(bool _leaf) : leaf(_leaf) {}
// 在节点中查找键值
int findKey(const T& key) {
int idx = 0;
while (idx < keys.size() && keys[idx] < key) ++idx;
return idx;
}
// 插入键值
void insertNonFull(const T& key) {
int idx = keys.size() - 1;
if (leaf) {
while (idx >= 0 && keys[idx] > key) {
keys[idx + 1] = keys[idx];
--idx;
}
keys[idx + 1] = key;
} else {
while (idx >= 0 && keys[idx] > key) --idx;
if (children[idx + 1]->keys.size() == 2 * t - 1) {
splitChild(idx + 1, children[idx + 1]);
if (keys[idx + 1] < key) ++idx;
}
children[idx + 1]->insertNonFull(key);
}
}
// 分裂子节点
void splitChild(int i, BTreeNode<T>* y) {
BTreeNode<T>* z = new BTreeNode<T>(y->leaf);
z->keys.resize(t - 1);
if (!y->leaf) {
z->children.resize(t);
}
for (int j = 0; j < t - 1; ++j) {
z->keys[j] = y->keys[j + t];
}
if (!y->leaf) {
for (int j = 0; j < t; ++j) {
z->children[j] = y->children[j + t];
}
}
y->keys.resize(t - 1);
if (!y->leaf) {
y->children.resize(t);
}
for (int j = keys.size(); j >= i + 1; --j) {
children[j + 1] = children[j];
}
children[i + 1] = z;
for (int j = keys.size() - 1; j >= i; --j) {
keys[j + 1] = keys[j];
}
keys[i] = y->keys[t - 1];
}
private:
static constexpr int t = 3; // B树的度数
};
// B树
template<typename T>
class BTree {
public:
BTree() : root(nullptr) {}
// 查找键值
bool search(const T& key) {
return root ? root->search(key) : false;
}
// 插入键值
void insert(const T& key) {
if (!root) {
root = new BTreeNode<T>(true);
root->keys.push_back(key);
} else {
if (root->keys.size() == 2 * BTreeNode<T>::t - 1) {
BTreeNode<T>* s = new BTreeNode<T>(false);
s->children.push_back(root);
s->splitChild(0, root);
int i = 0;
if (s->keys[0] < key) ++i;
s->children[i]->insertNonFull(key);
root = s;
} else {
root->insertNonFull(key);
}
}
}
private:
BTreeNode<T>* root;
};
int main() {
BTree<int> tree;
tree.insert(10);
tree.insert(20);
tree.insert(5);
tree.insert(6);
tree.insert(12);
tree.insert(30);
std::cout << "Search for 6: " << (tree.search(6) ? "Found" : "Not found") << std::endl;
std::cout << "Search for 7: " << (tree.search(7) ? "Found" : "Not found") << std::endl;
return 0;
}
这是一个简单的B树实现,包含了查找和插入操作。在实际应用中,可能需要更多的功能和优化。