Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector Erase Error

Tags:

c++

vector

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?

like image 294
LazySloth13 Avatar asked Apr 25 '13 15:04

LazySloth13


People also ask

What happens with vector erase?

vector::erase() erase() function is used to remove elements from a container from the specified position or range.

What is vector erase?

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.

Does vector erase change capacity?

King Of course the size have to be changed since an element is removed, but the capacity doesn't have to change.

Does vector erase destroy the object?

Yes. vector::erase destroys the removed object, which involves calling its destructor.


2 Answers

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);
like image 180
Andy Prowl Avatar answered Nov 15 '22 05:11

Andy Prowl


you have to pass an iterator to erase. So try

poss.erase(poss.begin() + random);
like image 20
TooTone Avatar answered Nov 15 '22 05:11

TooTone