容器emplace与push操作
# 容器emplace与push操作
Created: March 19, 2024 12:36 PM
在C++标准库中,**std::stack
的emplace
方法是一种用于在栈顶直接构造元素的高效方式。与push
方法相比,emplace
**可以避免临时对象的创建和复制或移动操作,因为它直接在栈顶的内存位置构造元素,接收的参数与元素构造函数的参数相同。
# emplace
方法的用法
假设有一个栈**std::stack<T>
,其中T
是栈中元素的类型。使用emplace
方法,你可以直接传递构造T
所需的参数,emplace
会利用这些参数在栈顶就地构造一个T
**类型的对象。
# 示例
考虑下面的示例,展示了**emplace
与push
**的不同:
cppCopy code
#include <iostream>#include <stack>#include <string>class Book {
public:
std::string title;
int year;
Book(const std::string& title, int year) : title(title), year(year) {
std::cout << "Book(const std::string&, int) called\n";
}
// 拷贝构造函数
Book(const Book& other) : title(other.title), year(other.year) {
std::cout << "Copy constructor called\n";
}
// 移动构造函数
Book(Book&& other) noexcept : title(std::move(other.title)), year(other.year) {
std::cout << "Move constructor called\n";
}
};
int main() {
std::stack<Book> books;
// 使用push结合临时对象
books.push(Book("The C++ Programming Language", 2013));
// 使用emplace直接在栈上构造对象
books.emplace("Effective Modern C++", 2014);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
在这个例子中,当使用**push
时,首先会调用Book
的构造函数来创建一个临时Book
对象,然后这个临时对象会被拷贝(或移动,如果支持移动语义)到栈中。相反,当使用emplace
时,Book
**对象会直接在栈上构造,避免了额外的拷贝或移动操作。
# 优点
- 性能:直接在容器内存位置构造元素,减少了复制或移动操作,提高了效率。
- 便捷性:允许直接传递构造参数给**
emplace
**方法,使代码更简洁。
**emplace
**方法是C++11及以后版本引入的,旨在提供更为高效的容器元素构造方式,特别是对于包含复杂对象的容器而言。
编辑 (opens new window)