I have a program with vector and it exits with code -1073741811. I think this happens becouse I erase the last element and should use pop_back instead, but how can i know is it the last element.
by the way why are they called vectors? they dont have much common with mathematical vectors.
It works for me (MinGW G++). What compiler are you using?
Those vectors come from physics, not mathematics.
The definition of vector used in CS comes from mathematics: http://en.wikipedia.org/wiki/Row_vector
Basically, a one-dimensional matrix.
When you add or remove items from a container using iterators it is better to reassign the iterator after every add or remove, because it is not sure that it will point in a legal memory position after that.
@Mitsakos: Actually, the erase method has defined behaviour.
@hamsterman: When you use erase on an iterator, that iterator will point to the next element in the vector after the operation. So your not correctly checking every element in your loop.
1 2 3 4
if ( (*it) == 3) {
v1.erase(it);
continue;
}
Edit: it should be it != v1.end() too, as it's a comparison not a numerical less than.
#include <vector>
#include <iostream>
usingnamespace std;
int main(){
vector<int> v1;
v1.push_back(5);
v1.push_back(4);
v1.push_back(3);
vector<int>::iterator it;
int count=0;//a counter to know how many items it searched in
for(it=v1.begin();it != v1.end();it++, count++){
if( (*it) == 3 ){
v1.erase(it);
if(count==0) ++count; // In the case that it is the first element the one you delete
it = v1.begin() + (--count);//after the erase we reassign it to the first element
//of the vector and we move the iterator as many positions
//as the we searched already (it must be reduced by one
//because we erased an element
}
}
return 0;
}
If I understand what you are trying to do you just want to remove every element with a certain value?
given
1 2
vector <int> values; // the list of values
int value; // the value to remove
do it yourself
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int original_size = values.size();
for (vector <int> ::iterator v = values.begin(); v != values.end();)
if (*v == value)
v = values.erase( v );
else
v++;
cout << (original_size -values.size()) << " items were removed. The list is now\n";
for (vector <int> ::iterator v = values.begin(); v != values.end(); v++)
cout << *v << ' ';
cout << endl;
return 0;
}
Use the STL
1 2 3
#include <algorithm>
#include <iterator>
...
1 2 3 4 5 6 7 8 9
int original_size = values.size();
values.erase( remove( values.begin(), values.end(), value ), values.end() );
cout << (original_size -values.size()) << " items were removed. The list is now\n";
copy( values.begin(), values.end(), ostream_iterator <int> ( cout, " " ) );
return 0;
}
I dont want to push_back something in the middle. I want that if some value( or its member) in the middle equals something I add stuff to the end of my vector.
like this:
1 2 3 4 5
for(it=v1.begin();it<v1.end();it++){
if (*it==3){
v1.push_back(7);
}
}