'std::vector<T>::iterator it;' doesn't compile

Max picture Max · Jun 29, 2010 · Viewed 9.1k times · Source

I've got this function:

    template<typename T>
    void Inventory::insertItem(std::vector<T>& v, const T& x)
    {
        std::vector<T>::iterator it; // doesn't compile
        for(it=v.begin(); it<v.end(); ++it)
        {
            if(x <= *it) // if the insertee is alphabetically less than this index
            {
                v.insert(it, x);
            }
        }
    }

and g++ gives these errors:

src/Item.hpp: In member function ‘void
yarl::item::Inventory::insertItem(std::vector<T, std::allocator<_CharT> >&, const T&)’:  
src/Item.hpp:186: error: expected ‘;’ before ‘it’  
src/Item.hpp:187: error: ‘it’ was not declared in this scope

it must be something simple, but after ten minutes of staring at it I can't find anything wrong. Anyone else see it?

Answer

Cogwheel picture Cogwheel · Jun 29, 2010

Try this instead:

typename std::vector<T>::iterator it;

Here's a page that describes how to use typename and why it's necessary here.