C++容器中emplace函数如何使用

   2024-10-05 2300
核心提示:emplace函数在C++容器中用于在容器中构造元素,它比insert函数更高效,因为它避免了额外的复制或移动操作。emplace函数接受的参

emplace函数在C++容器中用于在容器中构造元素,它比insert函数更高效,因为它避免了额外的复制或移动操作。emplace函数接受的参数和元素的构造函数参数相同,可以直接在emplace函数中传入这些参数以构造元素。

以下是使用emplace函数的示例:

#include <iostream>#include <vector>struct Person {    std::string name;    int age;        Person(std::string n, int a) : name(n), age(a) {}};int main() {    std::vector<Person> people;        // 使用emplace_back在vector中构造元素    people.emplace_back("Alice", 25);    people.emplace_back("Bob", 30);        // 遍历vector中的元素    for (const auto& person : people) {        std::cout << "Name: " << person.name << ", Age: " << person.age << std::endl;    }        return 0;}

在上面的示例中,我们定义了一个结构体Person,然后在vector中使用emplace_back函数构造了两个Person对象。通过使用emplace函数,我们直接将参数传递给Person的构造函数,避免了额外的复制或移动操作。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号