Page List

Search on the blog

2010年6月17日木曜日

Invincible Macros for C++(2) : For Iterator

When I started learning C++, I kind of thought that the "iterator" was really irritating.
What do you think?

I now think that iterators are similar to pointers and that I understand their convenience.
But it takes rather long time for you to write sources with iterators.

See the code below:
----------------------------------------------------
// e.g. 1
#include <iostream>
#include <vector>
#include <list>

using namespace std;

int main() {
   vector<int> vec;

   vec.push_back(1);
   vec.push_back(12);
   vec.push_back(167);

   vector<int>::iterator vec_p;
   for (vec_p = vec.begin(); vec_p < vec.end(); vec_p++)
      cout << *vec_p << endl;

   return 0;
}
----------------------------------------------------

In fact, you don't have to use iterators when you want to do stuff I listed above.
You can access to an element of the vector vec by using a pair of blankets and the corresponding index, like vec[i].
But you can't access to list's element this way.
So when you use list, you've got to utilize iterators like below:
----------------------------------------------------
// e.g. 2
#include <iostream>
#include <vector>
#include <list>

using namespace std;

int main() {
   list<int> lt;

   lt.push_back(1);
   lt.push_back(3);
   lt.push_back(5);

   list<int>::iterator lt_p;
   for (lt_p = lt.begin(); lt_p != lt.end(); lt_p++)
      cout << *lt_p << endl;

   return 0;
}
----------------------------------------------------
Please notice that the exit criteria is different from that of vector.
Iterator for list don't have the operator "<" or ">", so you have to use "!=".
Ummm, the iterator part is loooog, don't you think?
Then how's this?

----------------------------------------------------
// e.g. 3
#include <iostream>
#include <vector>
#include <list>

#define fori(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++)

using namespace std;

int main() {
   // for vector
   vector<int> vec;

   vec.push_back(1);
   vec.push_back(12);
   vec.push_back(167);

   fori(vec_p, vec)
      cout << *vec_p << endl;

   // for list
   list<int> lt;

   lt.push_back(1);
   lt.push_back(3);
   lt.push_back(5);

   fori(lt_p, lt)
      cout << *lt_p << endl;

   return 0;
}
----------------------------------------------------

0 件のコメント:

コメントを投稿