Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro for Iterator Loop for STL Iterables

Concept

So, I'm trying to define a macro to simplify the following code:

for (vector<TYPE>::iterator iter = iterable.begin(); 
             iter != iterable.end(); iter++)

and

for (map<TYPE, TYPE>::iterator iter = iterable.begin();
             iter != iterable.end(); iter++)

etc.

Existing Work

So far, I've got

#define every(iter, iterable) ::iterator iter = iterable.begin(); iter != iterable.end(); iter++
for (vector<TYPE> every(iter, iterable))

but I'd like to simplify this further.

Goal

Ideally, I'd like to be able to do

for (every(iter, iterable))

which means that I'd need to somehow get the class<TYPE> of the iterable object. Is this possible? If so, how can I do it?

Stipulations

  • This, ideally, needs to go into a (relatively) large codebase already set up to access the iterator object.
  • I am running on a compiler pre - C++11

Victory

#define every(iter, iterable) typeof(iterable.begin()) iter = iterable.begin(); iter != iterable.end(); iter++
for (every(iter, iterable))
like image 374
Patrick Perini Avatar asked Dec 09 '11 01:12

Patrick Perini


3 Answers

This answer does not depend on C++11, but it needs typeof, which some compilers may not have. Should work with any recent g++

#define For(iter, iterable) for(typeof((iterable).begin()) iter = (iterable).begin(); iter != (iterable).end(); ++iter)
like image 92
Aaron McDaid Avatar answered Sep 22 '22 02:09

Aaron McDaid


You can use for(auto iter = iterable.being(); iter != iterable.end(); iter++) if your compiler supports C++0x.

like image 26
fefe Avatar answered Sep 22 '22 02:09

fefe


If you are using C++11, you may use the new for syntax.

vector<double> v(9, 0.5);
auto total = 0.;
for (auto x: v) {
    total += x;
}

If you need a reference to modify the values, you may use:

vector<double> v(9, 0.5);
for (auto &x: v) {
    x = 5;
}

Just compile with the flag -std=c++0x.

like image 31
Ross Avatar answered Sep 24 '22 02:09

Ross