iterator problem
From: Pedro Graca (hexkid_at_hotpop.com)
Date: 10/14/04
- Next message: Michael Brooks: "Re: iterator problem"
- Previous message: Tabrez Iqbal: "Re: A problem about "vector" for c++ beginner"
- Next in thread: Michael Brooks: "Re: iterator problem"
- Reply: Michael Brooks: "Re: iterator problem"
- Reply: Alwyn: "Re: iterator problem"
- Reply: Chris \( Val \): "Re: iterator problem"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Michael Brooks: "Re: iterator problem"
- Previous message: Tabrez Iqbal: "Re: A problem about "vector" for c++ beginner"
- Next in thread: Michael Brooks: "Re: iterator problem"
- Reply: Michael Brooks: "Re: iterator problem"
- Reply: Alwyn: "Re: iterator problem"
- Reply: Chris \( Val \): "Re: iterator problem"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|