【发布时间】:2020-11-18 22:18:22
【问题描述】:
我正在尝试编写此代码,但这给出了错误
No matching member function for call to 'erase'clang(ovl_no_viable_member_function_in_call)
stl_vector.h(1317, 7): Candidate function not viable: no known conversion from 'int' to 'std::vector<int, std::allocator<int> >::const_iterator' (aka '__normal_iterator<const int *, std::vector<int, std::allocator<int> > >') for 1st argument
stl_vector.h(1344, 7): Candidate function not viable: requires 2 arguments, but 1 was provided
这是我的代码
#include <iostream>
#include <vector>
using namespace std;
int sockMerchant(int n, vector<int> ar) {
int pairCount=0;
for(int i=0;i<ar.size();i++)
{
for(int j=i+1;j<ar.size();j++)
{
if(ar[i]==ar[j])
pairCount++;
ar.erase(j);
}
}
return pairCount;
}
int main()
{
int n;
cin>>n;
vector <int> arr;
for(int i=0;i<n;i++)
{
int e=0;
cin>>e;
arr.push_back(e);
}
sockMerchant(n, arr);
}
如果可以的话,请告诉我为什么会出现这个错误,因为我采用了与 gfg 中相同的擦除功能方法。
【问题讨论】:
-
使用标准函数时出现的类似错误表明您应该查阅您最喜欢的有关您尝试调用的函数的文档(在这种情况下为
erase)。 -
所以没有办法或解决方法像我一样擦除元素?
-
Vector 不允许按索引擦除元素。为此,需要使用迭代器 - 但要小心,因为迭代器在 erase() 调用后变得无效。根据您要实现的具体目标,可能已经有 STL 算法可以做到这一点。如果你描述它是什么,有人可能会提供帮助。
-
你不能通过索引擦除元素,只能通过迭代器。不过要小心擦除循环中的元素。
erase()使迭代器无效,并递减size()。 StackOverflow 上有很多与此主题相关的问题,例如C++ nested for loop with erasing elements、Remove elements of a vector inside the loop、Erase in a loop with a condition in C++ 等 -
我很难弄清楚
sockMerchant()的真正意图是什么。它充满了逻辑问题,在不知道实际目标的情况下很难纠正。
标签: c++ vector compiler-errors