矢量擦除错误

Vector Erase Error

本文关键字:错误 擦除      更新时间:2023-10-16

我在c++中有以下代码:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
int main ()
{
    srand(time(0));
    int noOfElements = 9;
    for (int a = 0; a < 9; a++)
    {
        std::vector<int> poss;
        for (int a = 1; a <= 9; a++)
            poss.push_back(a);
        for (int b = 0; b < 9; b++)
        {
            int random = rand() % 9;
            std::cout << poss[random];
            poss.erase(random);
            noOfElements--;
        }
        std::cout << "n";
    }
}

但是当我运行它时,它返回这个:

error: no matching function for call to 'std::vector<int>::erase(int&)'

第13行

为什么会这样,我该如何纠正?

不能直接从vector容器中擦除 (vector是序列容器,而不是关联容器):需要为要擦除的元素提供一个迭代器。

要获得迭代器,可以:

  • 根据其值查找元素(例如使用std::find()),然后将返回的迭代器作为输入提供给erase()成员函数,或者
  • 通过对指向vector开头的迭代器(即由begin()成员函数返回的对象)应用偏移量来获得它。

第一种情况:

#include <vector>
#include <algorithm>
int main()
{
    std::vector<int> v { 1, 2, 3};
    auto i = std::find(begin(v), end(v), 2);
    v.erase(i);
}

上面的代码使用了一些c++ 11的特性。在c++ 03中,它看起来像这样:

#include <vector>
#include <algorithm>
int main()
{
    std::vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    std::vector<int>::iterator i = std::find(v.begin(), v.end(), 2);
    v.erase(i);
}

在第二种情况中,如果您知道向量内元素的索引(例如,pos),那么您可以通过这种方式轻松获得迭代器:

v.begin() + pos

或者(仅限c++ 11)您可以这样做:

next(begin(v), pos);

必须传递一个迭代器来擦除。所以尝试

poss.erase(poss.begin() + random);

Vector擦除函数接受迭代器而不是value。你还需要检查边界条件以确保你要擦除的索引没有越界。

std::vector<int>::iterator itr = poss.begin() + random;
if(itr != poss.end())
{
  poss.erase(itr);
}