erase() does not work on a STL vector inside a structure/object?

Viewed 213

I have an object that contains an STL vector. I start with the vector being size zero and use push_back to add to it. So, push_back works fine.

In my code, each element in the vector represents an atom. Thus the object this STL vector is inside is a "molecule".

When I try to remove an atom from my molecule i.e., erase one of the elements from the array, the erase() function does not work. Other methods do work such as size() and clear(). clear() removes all elements though, which is overkill. erase() is exactly what I want, but it doesn't work for some reason.

Here is an incredibly simplified version of my code. It does, however, represent the problem exactly.


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

class atomInfo 
{
/* real code has more variables and methods */
public:
    atomInfo () {} ;
};

class molInfo 
{
/* There is more than 1 atom per molecule */
/* real code has more variables and methods */
public:
    vector <atomInfo> atom;
    molInfo () {};
};

int main ()
{
    int i;
    molInfo mol;

    for( i=0; i<3 ; i++)
        mol.atom.push_back( atomInfo() );
    //mol.atom.clear() ; //Works fine
      mol.atom.erase(1) ; //does not work
}    

I get the following error when I use erase():

main.cpp: In function ‘int main()’: main.cpp:39:21: error: no matching function for call to ‘std::vector::erase(int)’ mol.atom.erase(1) ;

1 Answers

It looks like you thought std::vector::erase took an index from the start of the container.

It's not clear where you got this idea from, as it is not what the documentation says.

These functions work with iterators.

Fortunately, with vectors, you can get the effect you want by adding a number to an iterator.

Like this:

mol.atom.erase(mol.atom.begin() + 1);

Said documentation in fact does have an example to this effect.

Related