首页 > 代码库 > ch02
ch02
2.4 emplace_back减少内存拷贝
#include <vector> #include <map> #include <string> #include <iostream> using namespace std; struct Complicated { int year; double country; std::string name; Complicated(int a, double b, std::string c) :year(a), country(b), name(c) { cout << "is conrtusted" << endl; } Complicated(const Complicated & other) : year(other.year) , country(other.country) , name(std::move(other.name)) { cout << "is moved" << endl; } }; int main() { std::map<int, Complicated> m; int aInt = 4; double aDouble = 5.0; std::string aString = "C++"; cout << "--insert--" << endl; m.insert(std::make_pair(4, Complicated(aInt, aDouble, aString))); cout << "--emplace--" << endl; m.emplace(4, Complicated(aInt, aDouble, aString)); cout << "--emplce_back--" << endl; vector<Complicated> v; v.emplace_back(aInt, aDouble, aString); cout << "--push_back--" << endl; v.push_back(Complicated(aInt, aDouble, aString)); system("pause"); }
运行结果:
ch02
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。