C++ 用于排序的模板中的自定义比较器
一句背景;我是一名大学生,参加了“高级C++课程”的最后一周,这就是我的技能水平(不管这意味着什么)。这就是交易。这是我的SkipList类的定义。它通过排序“K”(键)存储数据,并保持数据类型“V”(值,可以是除此之外的任何值,只需假设int) 我的问题是我不知道如何用模板实现比较器。或者是比较器的任何东西。我还定义了SkipNode(未显示),这是可行的,但是如果不需要,我应该在节点中使用comparator模板吗C++ 用于排序的模板中的自定义比较器,c++,templates,C++,Templates,一句背景;我是一名大学生,参加了“高级C++课程”的最后一周,这就是我的技能水平(不管这意味着什么)。这就是交易。这是我的SkipList类的定义。它通过排序“K”(键)存储数据,并保持数据类型“V”(值,可以是除此之外的任何值,只需假设int) 我的问题是我不知道如何用模板实现比较器。或者是比较器的任何东西。我还定义了SkipNode(未显示),这是可行的,但是如果不需要,我应该在节点中使用comparator模板吗 我知道一个事实,我这里所说的是正确的(正如教授给我的答案)。如何(在我的in
我知道一个事实,我这里所说的是正确的(正如教授给我的答案)。如何(在我的
int main()
中)构造跳过列表?如何在我的insert()
fn中使用Comp?因为现在它只是硬编码为,也许可以向我们展示插入
函数的主体,您希望在其中使用比较器?“搜索”块中的“while”循环就是需要使用该Comp的。特别是“x->forward\ui]->key\uuComp
)。函子基本上是一个重载了操作符()
的类。而不是使用运算符
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;
};
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;
}
}