Trying to erase an element from a vector.
Use a list. A list is just as easy to use as a vector, and removing elements is very efficient. With a list when you remove() the element, it is gone. Your code traverses over your entire vector, so it doesn't look like you need random access, i.e. being able to use myVector[i]. If the word 'list' is too scary for you, just squint your eyes and pretend a list is a vector.
Also, when you use loops to traverse an STL container, you do it like this:
Code:
list<int> myList;
myList.push_back(10);
myList.push_back(20);
myList.push_back(30);
list<int>::iterator pos;
for(pos = myList.begin(); pos != myList.end(); ++pos)
{
cout<<*pos<<endl;
}
You can also use the predefined find() function to search an STL container for something:
Code:
#pragma warning( disable : 4786 )
#include <iostream>
#include <string>
#include <list>
#include <algorithm> //find()
using namespace std;
int main()
{
list<string> myList;
myList.push_back("Joe");
myList.push_back("Mary");
myList.push_back("Tim");
string name = "Mary";
list<string>::iterator result;
result = find(myList.begin(), myList.end(), name);
if(result != myList.end())
{
cout<<*result<<endl;
}
else
{
cout<<"Name not found."<<endl;
}
myList.remove("Mary");
result = find(myList.begin(), myList.end(), name);
if(result != myList.end())
{
cout<<*result<<endl;
}
else
{
cout<<"Name not found."<<endl;
}
return 0;
}