'std::vector::iterator it;'无法编译

发布于 2024-09-08 06:13:27 字数 794 浏览 1 评论 0原文

我有这个函数:

    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

它一定是简单的东西,但是在盯着它十分钟后我找不到任何错误。还有其他人看到吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔女人霸气范 2024-09-15 06:13:27

试试这个:

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

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

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.

少年亿悲伤 2024-09-15 06:13:27

你所做的事情效率很低。使用二分搜索代替:

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

What you are doing is inefficient. Use a binary search instead:

#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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文