Fixed minor issues pointed by static analysis tools and replaced for_each() by c++11 for-each loop.
Also added some checks on type conversion of layers container size.