c++

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

小樊
87
2024-07-25 15:55:11
栏目: 编程语言

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的构造函数,避免了额外的复制或移动操作。

0
看了该问题的人还看了