Sign in to follow this  

Erasing vectors by user input

Recommended Posts

Hi I'm stumped! I've made a vector and listed some items, I've made is so that i can add things to the list dependent on what the user types, but i now want to be able to remove things from that list also depending on what the user types. e.g. i don't want to erase the first or last item of the list and the list can be changed by the user so i don't know what number it is. I have a variable set up as oldGame which is altered by cin. I need to be able to remove what ever the user types from the list. I have a feeling it probably involves iterators but not sure, any help will be greatly appreciated thanks!

Share this post

Link to post
Share on other sites

#include <vector>
#include <algorithm> // for std::find
std::vector<int> Items;

// to delete 6:
std::vector<int>::iterator Iter = std::find(Items.begin(), Items.end(), 6);
if (Iter != Items.end())

Iterators are very useful, and the standard algorithms are too. Every container can be thought of as as sequence of items, from beginning to end. So iterators are a sort of inbetween to access containers in a standard way. This makes it possible for a piece of code to know nothing about the container and still operate on it, so most of the algorithms work with all the containers. And your code might too if you write it properly!

You can see above how you declare them. Items.end() gives the iterator one past the end of the container, so in a loop for example you can know when you reached the end.

An iterator 'points' to an element in the container, it can be thought of as a position in a sequence. To access the element: int AnItem = *Iter; or Iter->SomeMemberFunction();

Hope that makes sense, here is the sgi reference which I find handy to loop stuff up. Usually there are different ways to do things and I'm sure you can find some nifty algorithm or combinations of them to do it better.

Share this post

Link to post
Share on other sites
cheers for your help, I got it working eventually, has some problems but realised it was because I was using strings and entering things in that contained spaces so it caused errors, but working now. Thanks again!

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this