Добавление специализированных функций в контейнеры STL - PullRequest
0 голосов
/ 03 февраля 2012

У меня особый сценарий, и я пытаюсь добавить функциональность в «список» ...

#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, но это чисто научное занятие.

1 Ответ

4 голосов
/ 03 февраля 2012

Я думаю, что непосредственной причиной вашей ошибки является то, что вам нужно typename:

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

... потому что компилятор не понимает, что iterator это тип.

Но вы действительно не хотите получать от std::list, и вы не хотите писать свой собственный вид.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...