D
david wolf
I want to delete all even numbers in a vector, I am not sure if there's
any better way to do it. Following program is how I did it.
Look at the part of code beginning from
comments: //delete all even numbers.
My questions is actullay I have to put pos++ in the body of the
loop(also in if, else, statement). Can I somehow put it in
for(...;...;...).
Or can I use index instead of iterator in order to delete elements from
vector?
I just wish to know what's the most elegant way to do it.
Thanks
#include <iostream>
#include <vector>
main(){
int ar[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> tmpint;
//populate vector
for(int i=0; i<10; i++){
tmpint.push_back(ar);
}
//delete all even numbers
vector<int>::iterator pos;
for(pos=tmpint.begin(); pos != tmpint.end(); ){
if (*pos % 2 == 0)
tmpint.erase(pos);
else
pos++;
}
//display all elements in the vector
for(pos=tmpint.begin(); pos != tmpint.end();pos++ ){
cout<<*pos<<endl;
}
}
any better way to do it. Following program is how I did it.
Look at the part of code beginning from
comments: //delete all even numbers.
My questions is actullay I have to put pos++ in the body of the
loop(also in if, else, statement). Can I somehow put it in
for(...;...;...).
Or can I use index instead of iterator in order to delete elements from
vector?
I just wish to know what's the most elegant way to do it.
Thanks
#include <iostream>
#include <vector>
main(){
int ar[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> tmpint;
//populate vector
for(int i=0; i<10; i++){
tmpint.push_back(ar);
}
//delete all even numbers
vector<int>::iterator pos;
for(pos=tmpint.begin(); pos != tmpint.end(); ){
if (*pos % 2 == 0)
tmpint.erase(pos);
else
pos++;
}
//display all elements in the vector
for(pos=tmpint.begin(); pos != tmpint.end();pos++ ){
cout<<*pos<<endl;
}
}