Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using STL::vector<> with a class

Status
Not open for further replies.

PureMorning

Programmer
Feb 21, 2003
1
GB
Hi, I am making a particle system at the moment(Using c++ and openGL). At the moment I am using the std::vector in the STL to store my co-ordinates and other data for each particle. The problem is that I cannot seem to delete items from the vector<> I create. I know I need to use myVector.erase(ietm).

The problem is that I am using my own class called &quot;particle&quot; when I create the vector.

e.g. std::vector<particle> myData;

and so when I want to add a particle I do:

myData.push_back(myParticle);

This allows me to call methods from the particle class to move them etc. So when i come to delete a particle from the vector list how can i do it? I've tried using a for loop and saying:

myData.erase(i);

and I get this error:

d:\c++ work\particle mk2a\particle mk2\pSystem.cpp(66): error C2664: 'std::vector<_Ty,_Ax>::iterator std::vector<_Ty,_Ax>::erase(std::vector<_Ty,_Ax>::iterator)' : cannot convert parameter 1 from 'unsigned int' to 'std::vector<_Ty,_Ax>::iterator'
with
[
_Ty=particle,
_Ax=std::allocator<particle>
]
and
[
_Ty=particle,
_Ax=std::allocator<particle>
]


Does this mean I need to use an iterator? if so how do i use them? I've tried but got nowhere with this! I should also mention I dont want to delete all of the list items at once I only want to delete certain ones.

Any help is greatly appreciated!
Alan
 
Yes, it needs an iterator. Try this one: it deletes the 3rd element ie vector.begin() + 2.

Code:
#include <iostream>
#include <vector>
using namespace std;

main ()
{
   vector<int> dirn;

   dirn.push_back(10);
   dirn.push_back(20);
   dirn.push_back(30);
   dirn.push_back(40);

   dirn.erase (dirn.begin () + 2);

   for (vector<int>::iterator iter = dirn.begin(); iter != dirn.end(); ++iter)
   {
      cout << *iter << &quot; &quot;;
   }

   cout << endl;

   return 0;

}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top