为STL容器添加专门的功能

Adding specialized functionality to STL containers

本文关键字:功能 添加 STL      更新时间:2023-10-16

我有一个非常特殊的场景,我正在尝试为"list"添加功能。。。

#include <list>
template <typename T>
class ShortList : public std::list<T> {
  private:
    unsigned short max_items;
  public:
    // Getter and setter methods
    unsigned short getMaxItems (void) {
        return this.max_items;
    }
    void setMaxItems (unsigned short max_items) {
        this.max_items = max_items;
        return;
    }
    // Work methods
    void insertItemSorted (T item) {
        std::list<T>::iterator i, e = this.short_list.end();
        // Insertion sort O(n*max_items)
        for ( i = this.short_list.begin() ; i != e ; ++i ) {
            // Insert if smaller
            if ( item.getDiff() < (*i).getDiff() ) {
                this.short_list.insert(i, item);
                // Restrict list size to max items
                if ( this.short_list.size() > this.max_items ) {
                    this.short_list.erase(this.short_list.end());
                }
            }
        }
        return;
    }
}

我不明白我在这里做错了什么。以下是我的编译错误。。。

ShortList.cpp: In member function 'int ShortList<T>::insertItemSorted(T)':
ShortList.cpp:21: error: expected `;' before 'i'
ShortList.cpp:24: error: 'i' was not declared in this scope
ShortList.cpp:24: error: 'e' was not declared in this scope
ShortList.cpp: At global scope:
ShortList.cpp:35: error: expected unqualified-id at end of input

我觉得自己好像在不折不扣地遵循C++教程。有人能解释一下我哪里错了吗?我知道扩展STL容器的功能是一种糟糕的形式,但这纯粹是一种学术追求。

我认为您的错误的直接原因是您需要typename:

typename std::list<T>::iterator i, e = this.short_list.end();

因为编译器还没有意识到CCD_ 2是一个类型。

但您确实不想从std::list派生,也不想编写自己的排序。