容器之分类与各种测试(四)——multiset

multiset是可重复关键字的关联式容器,其与序列式容器相比最大的优势在于其查找效率相当高。(牺牲空间换取时间段)

 

 例程

#include<stdexcept>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<ctime>
#include<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_multiset(long& value)
{
	cout << "\ntest_multiset().......... \n";

	multiset<string> c;  	
	char buf[10];		
	clock_t timeStart = clock();								
	for(long i=0; i< value; ++i)
	{
		try
		{
			snprintf(buf, 10, "%d", rand());//multiset可以采用rand()方式填写元素,而set则不可以
			c.insert(string(buf));     				
		}
		catch(exception& p)
		{
			cout << "i=" << i << " " << p.what() << endl;	
			abort();
		}
	}
	cout << "milli-seconds : " << (clock()-timeStart) << endl;	
	cout << "multiset.size()= " << c.size() << endl;	//元素个数
	cout << "multiset.max_size()= " << c.max_size() << endl;	//max_size大小和内存大小正相关

	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_multiset(value);
	return 0;
}

 运行结果

 

 

猜你喜欢

转载自www.cnblogs.com/area-h-p/p/12012891.html