C++中vector的emplace_back()方法和push_back()方法
目录
- 1 基础知识
- 2 模板
- 3 工程化
1 基础知识
vector中push_back()需要复制对象,然后再将副本插入向量尾部;而emplace_back()无需复制,直接将对象插入向量尾部。
2 模板
#include <iostream>
#include <vector>using namespace std;int main() {vector<pair<int,int>> a;a.push_back({1,1});a.emplace_back(1,1);a.emplace_back(make_pair(1,1));for (auto [x, y] : a) {cout << "x = " << x << ", y = " << y << endl;}return 0;
}
上述代码输出,
x = 1, y = 1
x = 1, y = 1
x = 1, y = 1
3 工程化
暂无。。。