Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Set Array Using STL

📅 2010-Jul-05 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ algorithms, arrays, cpp, stl ⬩ 📚 Archive

A common initialization or cleanup operation when using arrays is set all its elements to a common value. It is typically done as:

for (int i = 0; i < SIZE; ++i)
    arr[i] = VAL;

The STL algorithm std::fill can be used to achieve the same with a single statement:

#include <algorithm>
std::fill( arr, arr + SIZE, VAL );