'std :: vector <T> :: iterator it;' 不编译

Max*_*Max 16 c++ stdvector

我有这个功能:

    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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

和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
Run Code Online (Sandbox Code Playgroud)

它必须是简单的东西,但在盯着它十分钟后我找不到任何错误.别人看到了吗?

Cog*_*eel 31

试试这个:

typename std::vector<T>::iterator it;
Run Code Online (Sandbox Code Playgroud)

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


fre*_*low 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);
}
Run Code Online (Sandbox Code Playgroud)

  • +1 - 打败了我.值得一提的是,由于当前代码在插入后没有突破循环,因此通常会在不需要的地方插入新项目的额外副本. (2认同)
  • @Jerry:更糟糕的是,如果向量的大小等于其容量,`insert`将使插入之前获得的所有迭代器无效,因此`++ it`将直接导入未定义的行为域. (2认同)