devxlogo

The fill() Algorithm

The algorithm fill() is declared in as follows:

 void fill(ForwardIterator f, ForwardIterator l, const T&);

The arguments f and l mark the sequence’s beginning and end, respectively. fill() fills the elements in the sequence with the fixed value T. This algorithm is useful when you want to initialize or reinitialize a sequence with a fixed value. For example, to initialize a char array, use fill() as follows:

 #include char *p = new char[100];std::fill(p, p+100, ''); // zero all characters

This is similar to calling memset(p, 0, 100). Note however, that fill() respects object semantics, unlike memset(). Therefore, you can use it to reinitialize a sequence of objects as well:

 #include #include #include std::vector < std::string> vs(100); std::fill(vs.begin(), vs.end(), "greetings!"); 

The vector vs initially contains 100 empty strings. fill() assigns a new value: “greetings!” to all the strings in the vector.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.