C + + fill () and Fill_n () function usage

Source: Internet
Author: User

The fill and Fill_n functions are part of the 12th generic algorithm for C + + primer and call them generation and mutation algorithms, meaning that these two functions can only operate on elements that already exist in the input range . Attempting to fill_n an empty container can result in a serious run-time error, so when writing to an element, check to see if the target is large enough to store the element to be written.

The fill function is to give the element of an interval a Val value. Function parameters: Fill (Vec.begin (), Vec.end (), Val); Val is the value that will be replaced.

The functions of the Fill_n function are: An iterator, a counter, and a value. The function starts with the element that the iterator points to, setting the specified number of elements to the given value.
Note: The Fill_n function cannot be called on an empty container without elements, but can be improved by the following method.

Fill_n (Vec.begin (), 10,val);

To ensure that the algorithm has enough elements to store the output data, we use the Insert iterator , insert iterator, which is an iterator that can add elements to the underlying container.

The program that uses Back_inserter needs to include the header file #include<iterator>, and the above program is rewritten as:

1 #include <iterator>  2 vector<int> VEC; // define an empty container 3 fill_n (Back_inserter (VEC), ten val);

In this program, each write value of the Fill_n () function is implemented by an insert iterator produced by Back_inserter. The effect is equivalent to push_back on the VEC, adding 10 elements at the end of the VEC.

C + + fill () and Fill_n () function usage (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.