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

multiset和multimap的具体区别在于,前者的key值就是自己存储的value,后者的key与value是分开的不相关的。

 

 例程

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

	multimap<long, string> c;  	
	char buf[10];

	clock_t timeStart = clock();								
	for(long i=0; i< value; ++i)
	{
		try 
		{
			snprintf(buf, 10, "%d", rand());//multimap 不可使用 [] 做 insertion 
			c.insert(pair<long,string>(i,buf));//使用标准库的进行插入操作   						
		}
		catch(exception& p) 
		{
			cout << "i=" << i << " " << p.what() << endl;	
			abort();
		}
	}
	cout << "milli-seconds : " << (clock()-timeStart) << endl;	
	cout << "multimap.size()= " << c.size() << endl;//元素个数
	cout << "multimap.max_size()= " << c.max_size() << endl;	//和计算机内存大小正相关

	long target = get_a_target_long();		
	timeStart = clock();		
	auto pItem = c.find(target);								
	cout << "c.find(), milli-seconds : " << (clock()-timeStart) << endl;	 
	if (pItem != c.end())
		cout << "found, value=" << (*pItem).second << endl;
	else
		cout << "not found! " << endl;	  
}
int main()
{
	long int value;
	cout<<"how many elements: ";
	cin>>value;
	test_multimap(value);
	return 0;
}

 运行效果

 

 

posted @ 2019-12-10 11:29  C_hp  阅读(200)  评论(0编辑  收藏  举报