标签:bsp ios algo unsigned lse mic char san lock
unordered-multiset是不定序关联式容器,其底部是通过哈希表实现功能。
(ps:黑色框就是bucket,白色框即为bucket上挂载的元素)
为了提高查找效率,bucket(篮子)的数量应当大于元素的个数,这是因为在bucket上悬挂的元素是通过单链表串起来的,而且一个unordered-multiset上一定会有很多bucket是没有悬挂元素,所以为了提升查找效率,当 元素个数>=bucket个数 时,bucket会自动扩充为原来的两倍左右,并且将元素重新哈希碰撞后再悬挂到bucket上。
例程
#include<stdexcept>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<ctime>
#include<unordered_set>
using namespace std;
long get_a_target_long()
{
long target = 0;
cout<<"target(0~"<<RAND_MAX<<"):";
cin>>target;
return target;
}
string get_a_target_string()
{
long target = 0;
char buf[10];
cout<<"target(0~"<<RAND_MAX<<"):";
cin>>target;
snprintf(buf, 10, "%ld", target);
return string(buf);
}
int compareLongs(const void* a, const void* b)
{
return (*(long*)a - *(long*)b);
}
int compareStrings(const void *a, const void *b)
{
if(*(string*)a > *(string*)b)
return 1;
else if(*(string*)a < *(string*)b)
return -1;
else
return 0;
}
void test_unordered_multiset(long& value)
{
cout << "\ntest_unordered_multiset().......... \n";
unordered_multiset<string> c;
char buf[10];
clock_t timeStart = clock();
for(long i=0; i< value; ++i)
{
try {
snprintf(buf, 10, "%d", rand());
c.insert(string(buf));
}
catch(exception& p) {
cout << "i=" << i << " " << p.what() << endl;
abort();
}
}
cout << "milli-seconds : " << (clock()-timeStart) << endl;
cout << "unordered_multiset.size()= " << c.size() << endl;
cout << "unordered_multiset.max_size()= " << c.max_size() << endl; //与计算机内存大小正相关
cout << "unordered_multiset.bucket_count()= " << c.bucket_count() << endl; //篮子个数
cout << "unordered_multiset.load_factor()= " << c.load_factor() << endl; //载重因子,元素个数/bucket个数
cout << "unordered_multiset.max_load_factor()= " << c.max_load_factor() << endl; //恒定为1
cout << "unordered_multiset.max_bucket_count()= " << c.max_bucket_count() << endl; //与计算机内存大小正相关
for (unsigned i=0; i< 20; ++i) {
cout << "bucket #" << i << " has " << c.bucket_size(i) << " elements.\n";
}
string target = get_a_target_string();
{
timeStart = clock();
auto pItem = find(c.begin(), c.end(), target); //比 c.find(...) 慢很多
cout << "std::find(), milli-seconds : " << (clock()-timeStart) << endl;
if (pItem != c.end())
cout << "found, " << *pItem << endl;
else
cout << "not found! " << endl;
}
{
timeStart = clock();
auto pItem = c.find(target); //比 std::find(...) 快很多
cout << "c.find(), milli-seconds : " << (clock()-timeStart) << endl;
if (pItem != c.end())
cout << "found, " << *pItem << endl;
else
cout << "not found! " << endl;
}
}
int main()
{
long int value;
cout<<"how many elements: ";
cin>>value;
test_unordered_multiset(value);
return 0;
}
运行一下
容器之分类与各种测试(四)——unordered-multiset
标签:bsp ios algo unsigned lse mic char san lock
原文地址:https://www.cnblogs.com/area-h-p/p/12015808.html