18

我有这个功能:

    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);
            }
        }
    }

并且 g++ 给出了这些错误:

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

应该是很简单的事情,但是看了十分钟,我也没发现什么不对劲的地方。还有人看吗?

4

2 回答 2

36

试试这个:

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

这是一个页面,描述了如何使用 typename以及为什么需要在这里。

于 2010-06-29T20:50:30.027 回答
8

你在做什么是低效的。改用二分搜索:

#include <algorithm>

template <typename T>
void insertItem(std::vector<T>& v, const T& x)
{
    v.insert(std::upper_bound(v.begin(), v.end(), x), x);
}
于 2010-06-29T21:05:45.827 回答