Zak
Zak

Reputation: 12653

Adding specialized functionality to STL containers

I have a very special scenario, and I'm trying to add functionality to "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;
    }
}

I can't understand what I'm doing wrong here. Here are my compile errors...

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

I feel as though I'm following a C++ tutorial to the letter. Can anyone explain where I've gone wrong? I know it's poor form to extend the functionality of a STL container, but this a is purely a scholarly pursuit.

Upvotes: 0

Views: 585

Answers (1)

Fred Larson
Fred Larson

Reputation: 62123

I think the immediate cause of your error is that you need typename:

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

... because the compiler doesn't realize that iterator is a type yet.

But you really don't want to derive from std::list, and you don't want to write your own sort.

Upvotes: 4

Related Questions