Using the emplace operation

Source: Internet
Author: User

The new C + + 11 standard introduces three new members,--emplace_front, Emplace, and Emplace_back, which construct rather than copy elements. These actions correspond to Push_front, insert, and push_back, allowing us to place the element in the container header, before a specified position, or at the end of the container.

When the push and insert member functions are called, we pass an object of the element type to them, which are copied into the container. When we call a Emplace member function, it is the constructor that passes the argument to the element type. Emplace members use these parameters to construct elements directly in the container-managed memory space. For example, suppose C saves the sales_data element:

Constructs a Sales_data object at the end of C//Sales_data constructor with three parameters C.emplace_back ("978-05", 25,15.99);//error: Three parameters not accepted Push_ Back version c.puah_back ("978-05", 25,15.99);//correct: Create a temporary Sales_data object to pass to Push_backc.push_back (Sales_data ("978-05", 25,15.99));

A new Sales_data object is created in both the call to Emplace_back and the second push_back call. When Emplace_data is called, objects are created directly in the container-managed memory space. Calling Push_back creates a local temporary object and presses it into the container.

The parameters of the Emplace function vary depending on the element type, and the parameter must match the constructor of the element type:

ITER points to an element in C, which holds the Sales_data element c.emplace_back ();//uses the Sales_data default constructor c.emplace (ITER, "999-99999999");//Use Sales _data (String)//use Sales_data to accept an ISBN, a count, and a price constructor C.emplace_front ("978-423423", 432,43.99);

Note: The Emplace function constructs elements directly in the container. The arguments passed to the Emplace function must match the constructor of the element type.

Using the emplace operation

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.