iterator problem

From: Pedro Graca (hexkid_at_hotpop.com)
Date: 10/14/04


Date: 14 Oct 2004 16:05:51 GMT

I'm getting ahead of the "Accelerated C++" book I have at home (it's a
quiet [boring] day here at work).

Anyway ... I've heard so much about iterators I wanted to see what I
could do.

cpp$ echo; echo; cat itertest.cpp

#include <iostream>
#include <vector>
using namespace std;

const bool is_negative(const int);
void remove_values(vector<int> &, const bool (*)(const int));

int main() {
  vector<int> arr;
  
  for (int i=0; i<10; ++i) arr.push_back(3-i);
  arr.push_back(4);

  cout << "Before: ";
  for (size_t i=0; i<arr.size(); ++i) cout << arr[i] << ", ";
  cout << endl;
  
  remove_values(arr, is_negative);
  
  cout << " After: ";
  for (size_t i=0; i<arr.size(); ++i) cout << arr[i] << ", ";
  cout << endl;
}

const bool is_negative(const int v) {
  return v<0;
}

void remove_values(vector<int> & data, const bool (*validate)(const int)) {
  vector<int>::iterator i = data.begin();
  while (i != data.end()) {
   /* my first attempt here was :
    *
    * if (validate(*i)) data.erase(i);
    * ++i;
    *
    * but it didn't work, so I changed it to
    * the following
    */
    if (validate(*i)) {
     /* delete this element, *after* advancing the iterator
      */
      vector<int>::iterator j = i;
      ++i;
      data.erase(j);
    } else {
      ++i;
    }
  }
}

cpp$ g++ -W -Wall -ansi -pedantic itertest.cpp
cpp$ ./a.out
Before: 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, 4,
 After: 3, 2, 1, 0, -2, -4, -6, 4,

What am I doing wrong in remove_values()?
I realize probably I should also use iterators to print the data ...
Can I mix iterators (in remove_values()) and [indexes] (in the code to
print)?

After typing these questions I think maybe the iterator is the wrong
type.
Probably the book explains how to do what I want, but ... the post is
ready :-)

-- 
USENET would be a better place if everybody read:
http://www.expita.com/nomime.html
http://www.netmeister.org/news/learn2quote2.html
http://www.catb.org/~esr/faqs/smart-questions.html


Relevant Pages

  • Re: Could use some help...:)
    ... cout << endl ... int B::operator (unsigned row, unsigned column) ...
    (comp.lang.cpp)
  • valarray iterators?
    ... I've did some some numerical programs in C/C++ before, ... const int MAX=10; ... cout << endl; ...
    (comp.lang.cpp)
  • STL set class
    ... set <int> s0; ... // Create an empty set s1 with the key comparison ... cout << endl; ...
    (microsoft.public.vc.stl)
  • Cant see DLL symbols in debugger.
    ... APPIMPEXP extern int applic_datum; ... << endl; ... cout << endl; ... Dynlib2 is similar to dynlib1. ...
    (microsoft.public.vstudio.development)
  • Help preventing weak software
    ... template <typename T> ... int main ... cout << endl; ...
    (comp.lang.cpp)