C++ Algorithm fill_n()C++ Algorithm fill_n() function is used to assign a new value to a specified number of elements in a range beginning with a particular element. It means in fill_n(), we specify beginning position, number of elements to be filled and value to be filled. SyntaxParameterfirst: An output iterator pointing the position of the first element in the range to be assigned the value val. val: Value which is used to fill the range. n: Number of elements to fill it may be signed or unsigned integer type. Return valueThe first version of fill_n() return none and the second version of fill_n() return an iterator pointing to the element that follows the last element to be filled. ComplexityComplexity is linear in n. And assigns a value to each element. Data racesThe first n object in the range pointed by first are modified. Exception safetyThis function throws an exception if the element assignments or the operation on an iterator throws an exception. Please note that invalid parameters cause an undefined behavior. Example 1Let's see the simple example to demonstrate the use of fill_n(): Output: 3,3,3,3,3,3,3,3,3,3, Example 2Let's see another simple example: Output: vector v = ( 0 0 0 0 0 0 0 0 0 ) modified v = ( 1 1 1 0 0 0 0 0 0 ) modified v = ( 1 1 1 2 2 2 0 0 0 ) modified v = ( 1 1 1 2 2 2 3 3 3 ) Example 3Let's see another simple example: Output: 1 1 1 0 0 0 0 0 1 1 1 4 4 4 0 0 Example 4Let's see another simple example: Output: Vector vec data: 10 11 12 13 14 15 16 17 18 19 20 Operation: fill_n(vec.begin() + 3, 6, 9) Modified vec data: 10 11 12 9 9 9 9 9 9 19 20 Next TopicC++ Algorithm |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India