本篇学习unordered_set的插入操作具体的函数有:
(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 = 10000;
unordered_set<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("Generalization" + 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_set<string> set2;
double startTime2 = clock();
for(int i = 0; i < count; i++)
{
set2.emplace("Generalization" + std::to_string(i));
}
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_set<string> set3;
auto set3it = set3.begin();
double startTime3 = clock();
for(int i = 0; i < count; i++)//214748
{
set3.emplace_hint(set3it, "Generalization" + std::to_string(i));
}
double endTime3 = clock();
cout << "set3.size = " << set3.size() << " 3 run time is: " << (double)(endTime3 - startTime3) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
unordered_set<string>::iterator iter1 = set3.emplace_hint(set3it, "scott");
cout << "iter1======" << iter1->data() << endl;
}
int main()
{
insertOperator();
cout << "Hello, world!" << endl;
return 0;
}
运行结果:
参考: