Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Intermediate
Sep 8, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

The fill() Algorithm

The algorithm fill() is declared in <algorithm> 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 <algorithm>
char *p = new char[100];
std::fill(p, p+100, '\0'); // 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 <algorithm>
#include <vector>
#include <string>

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.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date