Improving std::for_each

With C++11 we get the `std::for_each` for enumerating the iterators of a container. It is a useful helper that you don't need to worry about the "off-by-1" errors and trying to dereference the end iterators by mistake which can be undefined behaviour in most of the compilers.

Old Style of iterating over containers
std::for_each gives us light

But with for_each, I lose the way to keep track of the INDICES of the array. One way is to keep a separate index variable and keep updating it every time we are in the lambda.


So I have create a function called "enumerate" (Python users might get triggered ??)

It will keep updating the variable automatically.

std::enumerate definition

Basically it is a type safe function for enumerating the container with an index in handy. Yes there is a problem that the index is always starting from zero, no matter where you want to start in the container. But that is okay for me. I know where I'm in my container I can update the index to my use case. So now you can just do this

Yay!


The type traits that I've used to define the function std::is_iterator, are also not present in the standard library. So I've created them anyway to do this. This is published as a Gist on GitHub ( https://gist.github.com/bradley101/638a735e7006717e849a7152cc6ac787 )


Let me know what you guys think about this, and if something can be improved.

要查看或添加评论,请登录

Shantanu Banerjee的更多文章

  • Template Meta-programming in C++

    Template Meta-programming in C++

    What it is not It is not some magic wand that will tell your C++ expertise. Many of us don't feel the need to use…

社区洞察

其他会员也浏览了