moving elements in vectors
From: Peter (peter_at_peter.com)
Date: 07/30/04
- Next message: Paul: "Re: school assignment annoyance"
- Previous message: Alwyn: "Re: [C] strlen, strcat and malloc"
- Next in thread: Alwyn: "Re: moving elements in vectors"
- Reply: Alwyn: "Re: moving elements in vectors"
- Reply: Chris \( Val \): "Re: moving elements in vectors"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 30 Jul 2004 10:50:37 +0000 (UTC)
Hi, I have the equivalent to the following code. Assuming the values
within values fluctuates and the condition on which an element is erased
captures more than just one element ie multiple conditions, why would it
cause an access violation? All I wish to do is move an element from the
beginning of the vector to the end by erasing it and then adding it back
in? Also why does the output show a print out of 5 twice at the end?
Thanks for any help.
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> temp;
vector<int> values;
for(int i = 0; i < 5; i++)
values.push_back(i + 1);
for(vector<int>::iterator it = values.begin(), endit = values.end(); it
!= endit; ++it) {
int x = *it;
cout << "out condition" << endl;
cout << "it value=" << x << endl;
if(x == 3) {
cout << "in condition" << endl;
it = values.erase(it);
--it;
cout << "after erasing it=" << *it << endl;
temp.push_back(x);
}
}
copy(temp.begin(), temp.end(), back_inserter(values));
system("pause");
return 0;
}
- Next message: Paul: "Re: school assignment annoyance"
- Previous message: Alwyn: "Re: [C] strlen, strcat and malloc"
- Next in thread: Alwyn: "Re: moving elements in vectors"
- Reply: Alwyn: "Re: moving elements in vectors"
- Reply: Chris \( Val \): "Re: moving elements in vectors"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|