矢量擦除错误 [英] Vector Erase Error
问题描述
我在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>占有
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.erase(random);
noOfElements--;
}
std :: cout<< \\\
;
}
}
但是当我运行它时, / p>
错误:没有匹配的函数调用'std :: vector< int> :: erase(int&)'
为什么是这样和如何?
解决方案您不能直接从向量中删除值 ,不是关联容器):您需要为要擦除的元素提供一个迭代器。
要获得迭代器,您可以:
- 元素(例如,使用
std :: find()
),然后将返回的迭代器提供给 erase()
成员函数,或
- 通过向迭代器应用偏移量您的向量的开头(即由
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)您可以:
I have the following code in 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";
}
}
Yet when I run it, it returns this:
error: no matching function for call to 'std::vector<int>::erase(int&)'
for line 13.
Why is this and how can I correct it?
解决方案 You cannot erase values from a vector directly (vectors are sequence containers, not associative containers): you need to provide an iterator to the element that you want to be erased.
In order to get an iterator, you may either:
- find the element based on its value (e.g. by using
std::find()
) and then provide the returned iterator in input to the erase()
member function, or
- get it by applying an offset to the iterator which points to the beginning of your vector (i.e. the object returned by the
begin()
member function).
In the first case:
#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);
}
The above code uses some C++11 features. In C++03, it would look as follows:
#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);
}
In the second case, if you know the index of your element inside the vector (say, pos
), then you can easily get an iterator this way:
v.begin() + pos
Alternatively (C++11 only) you could do:
next(begin(v), pos);
这篇关于矢量擦除错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!