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

set和multiset的去别在于前者的key值不可以重复,所以用随机数作为其元素进行插入时,遇到重复元素就会被拒绝插入(但是程序不会崩溃)。

 例程

#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_set(long& value)
{
	cout << "\ntest_set().......... \n";

	set<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 << "set.size()= " << c.size() << endl;//元素个数
	cout << "set.max_size()= " << c.max_size() << endl;	   //和计算机内存大小相关

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

 查看运行结果是否和我们预测的一样

 要求插入100万个元素,但是由于set本身不容许重复的特性,实际仅插入了998385个元素。

猜你喜欢

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