Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stdvector

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?

like image 357
Max Avatar asked Jun 29 '10 20:06

Max


People also ask

Can you dereference an iterator?

Dereferencing: An input iterator can be dereferenced, using the operator * and -> as an rvalue to obtain the value stored at the position being pointed to by the iterator. 4. Incrementable: An input iterator can be incremented, so that it refers to the next element in the sequence, using operator ++().

How do I assign an iterator in C++?

Operator= -- Assign the iterator to a new position (typically the start or end of the container's elements). To assign the value of the element the iterator is pointing at, dereference the iterator first, then use the assign operator.


1 Answers

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.

like image 93
Cogwheel Avatar answered Oct 05 '22 08:10

Cogwheel