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.
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.
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?
iterator
object.#define every(iter, iterable) typeof(iterable.begin()) iter = iterable.begin(); iter != iterable.end(); iter++
for (every(iter, iterable))
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)
You can use for(auto iter = iterable.being(); iter != iterable.end(); iter++)
if your compiler supports C++0x.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With