refactor code by using STL algorithm