moving elements in vectors

From: Peter (peter_at_peter.com)
Date: 07/30/04


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;
}



Relevant Pages

  • Re: moving elements in vectors
    ... | within values fluctuates and the condition on which an element is erased ... | int main{ ... | vectortemp; ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Read File into multi-dimensional array ignore whitespace
    ... value, followed by a single whitespace, followed by another four-digit ... The first regex match captures just the line number field, ... context later on, or force this context by iterating over each value ... (note that int without arguments, like most Perl builtins, simply ...
    (comp.lang.perl.misc)