向量.erase错误c2664 [英] vector .erase error c2664

查看:452
本文介绍了向量.erase错误c2664的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图迭代通过一个向量和擦除从它的特定项目。我正在工作形式向量的结束,以便我不打乱迭代器,因为项目被删除,但当我尝试编译它抛出一个错误。我浏览了一些其他的帖子,这个相同的错误,但没有看到任何适用于我的情况,或者如果我没有抓住它,我还是相当新的C + +和编程一般。下面是一个简单的代码示例来说明我的问题。

I am trying to iterate through a vector and erase specific items from it. I'm working form the end of the vector down so that I don't mess up the iterator as items are removed, but when I try to compile it's throwing an error. I looked through some of the other posts with this same error but didn't see anything that applied to my situation, or if there was I didn't catch it, I'm still pretty new to C++ and programming in general. Below is a sample of a simpler code to illustrate my problem.

#include <iostream>
#include <vector>

using namespace std;

int vectorErase(vector<int>, int &);

int main()
{
    vector<int> test;

    for(int i=0; i<11;i++)
    {
        test.push_back(i);
        cout<<test[i];
    }

    for(int i=10;i<=0;i--)
    {
        vectorErase(test, i);
        cout<<test[i];
    }

    system("pause");
    return 0;
}

int vectorErase(vector<int> test, int &iterat)
{
    if(test[iterat]>6)
    {
        test.erase(iterat);
    }
    return 0;
} 

任何帮助都是很好的

推荐答案

代码中最直接的问题是:

The most immediate problems in your code are:


    < ,因此原始文件不会被修改。
  • 正确使用 erase()它会向序列中的下一个元素返回一个迭代器,您不能擦除它。这意味着如果你使用迭代器和删除一个元素,你不需要(也不应该)递增迭代器。

  • Passing your vector by value, so the original is never modified.
  • Not using erase() properly. It returns an iterator to the next element in the sequence, which you did not erase (yet). This means if you use iterators and remove an element, you need not (and should not) increment the iterator. An example is forth-coming.
  • In conjunction with the above, simply, you're not using iterators, and you should be.

您的代码可以没有函数,只需这样做:

Your code could do without the function and simply do this:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> test;

    for(int i=0; i<11;i++)
    {
        cout << i << ' ';
        test.push_back(i);
    }
    cout << '\n';

    for(auto it = test.begin(); it != test.end();)
    {
        if (*it > 6)
            it = test.erase(it);
        else
        {
            cout << *it << ' ';
            ++it;
        }
    }
    cout << '\n';

    return 0;
}

输出

0 1 2 3 4 5 6 7 8 9 10 
0 1 2 3 4 5 6 

我强烈建议你花几天时间使用迭代器。从简单的开始(像这个例子)。

I strongly advise you spend a few days working with iterators. Start with something simple (like this example).

这篇关于向量.erase错误c2664的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆