Sorry but your example is slightly wrong. Try this small modification and input 5. It should remove all 5-s, shouldn't it? But it doesn't! After each erasure you skip one item - and if you skip the last you may well increment names.end() and enter undefined land.
Code:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;
int main(int argc, char** argv){
vector<string> names;
names.push_back("5");
names.push_back("5");
names.push_back("15");
string age;
vector<string>::iterator it;
cin>>age;
for(it=names.begin();it < names.end();it++){
if(*it == age){
names.erase(it);
}
}
for(it=names.begin();it<names.end();it++){
cout<<*it<<endl;
}
return EXIT_SUCCESS;
}
For your information, undefined behaviour doesn't mean that the program will crash or do otherwise an obviously wrong thing. Undefined behaviour means that your program may appear to work correctly - until the slightest change in any unrelated part of the program. You may get away with out-of-bound accesses unpunished, for example because the vector overallocates and that memory still belongs to it, although it is unused.
That is, you have to know what you are doing.
As to whether [] inserts for vector, would it be that hard to find out:
Code:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v;
v.reserve(2);
v[0] = 10;
std::cout << v.size();
}
This should print (at least) 1 according to your theory, but the vector nevertheless reports that it contains 0 items. This code just accesses an item out of the vector's bounds (and it probably gets away with it, since that memory is reserved - not making this code correct, though).
As to correcting your erase example, try this:
Code:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;
int main(int argc, char** argv){
vector<string> names;
names.push_back("5");
names.push_back("5");
names.push_back("15");
string age;
vector<string>::iterator it;
cin>>age;
for(it=names.begin();it < names.end();){
if(*it == age){
it = names.erase(it);
}
else {
++it;
}
}
for(it=names.begin();it<names.end();it++){
cout<<*it<<endl;
}
return EXIT_SUCCESS;
}
As you can see the loop is not as trivial as that. Therefore it is a better idea to use std algorithms for such tasks (particularly since the erase-remove combo has better complexity and does a lot less copying for larger datasets).