首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::list::emplace_back

template< class... Args > void emplace_back( Args&&... args );

(since C++11) (until C++17)

template< class... Args > reference emplace_back( Args&&... args );

(since C++17)

将一个新元素附加到容器的末尾。元素是通过std::allocator_traits::construct,它通常使用Plant-New来在容器提供的位置构造就地元素。争论args...被转发给构造函数的std::forward<Args>(args)......

没有迭代器或引用无效。

参数

args

-

arguments to forward to the constructor of the element

类型要求

-T%28容器%27s元素类型%29必须满足EmplaceConstrucable的要求。

返回值

(none)

(until C++17)

A reference to the inserted element.

(since C++17)

复杂性

常量。

例外

如果引发异常,则此函数不具有%28强异常保证%29的效果。

下面的代码使用emplace_back添加类型对象President转到std::list.它证明了emplace_back将参数转发到President构造函数,并演示如何使用emplace_back使用时,避免了所需的额外复制或移动操作。push_back...

二次

代码语言:javascript
复制
#include <list>
#include <string>
#include <iostream>
 
struct President
{
    std::string name;
    std::string country;
    int year;
 
    President(std::string p_name, std::string p_country, int p_year)
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)
    {
        std::cout << "I am being constructed.\n";
    }
    President(President&& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    {
        std::cout << "I am being moved.\n";
    }
    President& operator=(const President& other) = default;
};
 
int main()
{
    std::list<President> elections;
    std::cout << "emplace_back:\n";
    elections.emplace_back("Nelson Mandela", "South Africa", 1994);
 
    std::list<President> reElections;
    std::cout << "\npush_back:\n";
    reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));
 
    std::cout << "\nContents:\n";
    for (President const& president: elections) {
        std::cout << president.name << " was elected president of "
                  << president.country << " in " << president.year << ".\n";
    }
    for (President const& president: reElections) {
        std::cout << president.name << " was re-elected president of "
                  << president.country << " in " << president.year << ".\n";
    }
}

二次

产出:

二次

代码语言:javascript
复制
emplace_back:
I am being constructed.
 
push_back:
I am being constructed.
I am being moved.
 
Contents:
Nelson Mandela was elected president of South Africa in 1994.
Franklin Delano Roosevelt was re-elected president of the USA in 1936.

二次

另见

push_back

adds an element to the end (public member function)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券