replace some loops with STL algorithms