插入结构体时,emplace比insert少一次拷贝构造,推荐使用emplace
// map_emplace.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct Clinet {
string host;
int port;
Clinet(string hostParam, int portParam):host(hostParam),port(portParam)
{
cout << "Clinet Construct" << endl;
}
Clinet(const Clinet &other) :host(other.host), port(other.port)
{
cout << "Clinet Copy Construct" << endl;
}
};
int main()
{
map<int, struct Clinet> mapTmpVariable;
mapTmpVariable.emplace(1, Clinet("192.168.100.1", 1000));
mapTmpVariable.emplace(2, Clinet("192.168.100.2", 1001));
mapTmpVariable.emplace(3, Clinet("192.168.100.3", 1002));
cout << "size:" << mapTmpVariable.size() << endl;
mapTmpVariable.insert(std::pair<int, struct Clinet>(4, Clinet("192.168.100.3", 1002)));
cout << "size:" << mapTmpVariable.size() << endl;
}
版权声明:本文为weixin_41146595原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。