Erasing vectors by user input

Started by
1 comment, last by Slyfox 17 years, 12 months ago
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!
Advertisement

#include <vector>
#include <algorithm> // for std::find
std::vector<int> Items;
Items.push_back(2);
Items.push_back(6);
Items.push_back(8);

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


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.
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!

This topic is closed to new replies.

Advertisement