Jump to content
  • Advertisement
Sign in to follow this  

Erasing vectors by user input

This topic is 4537 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!