一句背景;我是一名大学生,并且在“高级C ++”的最后一周,这是我的技能水平(无论那意味着什么)。所以这里是交易。这是我的SkipList类的定义。它通过排序'K'(键)存储数据并保存数据类型'V'(值可以是任何东西,但为此只假设为int)。
我的问题是我不知道如何使用模板实现Comparator。或者与比较器有关。我也定义了SkipNode(未显示)并且可以工作,但如果它从不需要,我应该在Node中有比较器模板吗?
我知道我在这里所拥有的是正确的(正如教授给我的那样)。我如何(在我的int main()
中)构造skip_list?如何在insert()
fn中使用Comp?因为现在它只是硬编码为<
。
我知道在没有进一步了解项目的情况下回答这些稍微更高级的问题是多么困难,所以在此之前提前感谢您的帮助。如果还有什么我可以告诉你的,请告诉我。
template <typename K, typename V, typename Comp = std::less<K> >
class Skip_list {
public:
Skip_list<K, V, Comp> (const Comp& c = Comp());
~Skip_list<K, V, Comp> ();
// NON-MODIFYING MEMBER FUNCTIONS
void print ();
SkipNode<K, V, Comp>* find (K searchKey);
// MODIFYING MEMBER FUNCTIONS
void insert (K searchKey, V newValue);
void erase (K searchKey);
private:
// POINTER TO FIRST NODE
SkipNode<K, V, Comp>* head;
// POINTER TO LAST NODE
SkipNode<K, V, Comp>* NIL;
// IMPLICITLY USED MEMBER FUNCTIONS
int randomLevel ();
int nodeLevel(const std::vector<SkipNode<K, V, Comp>* >& v);
SkipNode<K, V, Comp>* makeNode (K key, V val, int level);
// DATA MEMBERS
float probability;
int maxLevel;
};
/ *整个行程O'CODE * /
template <typename K, typename V, typename Comp >
void Skip_list<K, V, Comp>::insert(K searchKey, V newValue) {
// REASSIGN IF NODE EXISTS
SkipNode<K, V, Comp>* x = nullptr;
x = find(searchKey);
if (x) {
x->value_ = newValue;
return;
}
// VECTOR OF POINTERS THAT NEEDS TO BE UPDATED TO ACCOUNT FOR THE NEW NODE
std::vector<SkipNode<K, V, Comp>* > update(head->forward_);
int currentMaximum = nodeLevel(head->forward_);
x = head;
// SEARCH THE LIST
for (int i = currentMaximum; i-- > 0;) {
while (x->forward_[i] != nullptr && x->forward_[i]->key_ < searchKey) {
x = x->forward_[i];
}
update[i] = x;
}
x = x->forward_[0];
// CREATE NEW NODE
int newNodeLevel = 1;
if (x->key_ != searchKey) {
newNodeLevel = randomLevel();
int currentLevel = nodeLevel(update);
if (newNodeLevel > currentLevel) {
for (int i = currentLevel + 1; i < newNodeLevel; ++i) {
update[i] = head;
}
}
x = makeNode(searchKey, newValue, newNodeLevel);
}
// CONNECT POINTERS OF PREDECESSEORS AND NEW NODE TO SUCCESSORS
for (int i = 0; i < newNodeLevel; ++i) {
x->forward_[i] = update[i]->forward_[i];
update[i]->forward_[i] = x;
}
}