unordered_multiset学习之插入数据操作insert,emplace ,emplace_hint
本篇学习unordered_multiset的插入数据操作,具体的函数如下:
(C++11) | 插入元素或结点 (C++17 起) (公开成员函数) |
(C++11) | 原位构造元素 (公开成员函数) |
(C++11) | 使用提示原位构造元素 (公开成员函数) |
代码示例
#include <unordered_set>
#include <string>
#include <time.h>
#include <iostream>
using namespace std;
void insertOperator()
{
const int count = 100000;
unordered_multiset<string> set1;
cout << "set1.size = " << set1.size() << " set1.empty = " << set1.empty() << " set1.max_size = " << set1.max_size() << endl;
//1.insert 插入元素或结点
double startTime1 = clock();
for(int i = 0; i < count; i++)
{
set1.insert("camel");// + std::to_string(i)
}
double endTime1 = clock();
cout << "set1.size = " << set1.size() << " 1 run time is: " << (double)(endTime1 - startTime1) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
//set1.clear();
//2.emplace原位构造元素
unordered_multiset<string> set2;
double startTime2 = clock();
for(int i = 0; i < count; i++)
{
set2.emplace("camel");
}
double endTime2 = clock();
cout << "set2.size = " << set2.size() << " 2 run time is: " << (double)(endTime2 - startTime2) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
//3.emplace_hint使用提示原位构造元素
unordered_multiset<string> set3;
auto set3it = set3.begin();
double startTime3 = clock();
for(int i = 0; i < count; i++)//214748
{
set3.emplace_hint(set3it, "camel");
}
double endTime3 = clock();
cout << "set3.size = " << set3.size() << " 3 run time is: " << (double)(endTime3 - startTime3) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
unordered_multiset<string>::iterator iter1 = set3.emplace_hint(set3it, "scott");
cout << "iter1======" << iter1->data() << endl;
}
int main()
{
insertOperator();
cout << "Hello, world!" << endl;
return 0;
}
运行结果:
参考:
https://zh.cppreference.com/w/cpp/container/unordered_multiset