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?
vector::erase() erase() function is used to remove elements from a container from the specified position or range.
The vector::erase() function is a function that is implemented in the vector class and used to remove elements one-by-one. This function erases the element from a desired position.
King Of course the size have to be changed since an element is removed, but the capacity doesn't have to change.
Yes. vector::erase destroys the removed object, which involves calling its destructor.
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:
std::find()
) and then provide the returned iterator in input to the erase()
member function, or 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);
you have to pass an iterator to erase. So try
poss.erase(poss.begin() + random);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With