容器之分类与各种测试(三)——slist的用法

slist和forward_list的不同之处在于其所在的库

使用slist需要包含

#include<ext\list>

 而使用forward_list则需要包含

#include<forward_list>

 剩余两者调用的API基本相同

例程

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

	_gun_cxx::slist<string> c;  	
	char buf[10];

	clock_t timeStart = clock();								
	for(long i=0; i< value; ++i)
	{
		try 
		{
			snprintf(buf, 10, "%d", rand());
			c.push_front(string(buf));  	//由于效率原因,forward_list不提供push_back方法
		}
		catch(exception& p)
		{
			cout << "i=" << i << " " << p.what() << endl;	
			abort();
		}
	}
	cout << "milli-seconds : " << (clock()-timeStart) << endl;	
	cout << "slist.max_size()= " << c.max_size() << endl;  //536870911
	cout << "slist.front()= " << c.front() << endl;	


	string target = get_a_target_string();	
	timeStart = clock();			
	auto pItem = find(c.begin(), c.end(), target);	
	cout << "std::find(), milli-seconds : " << (clock()-timeStart) << endl;		

	if (pItem != c.end())
		cout << "found, " << *pItem << endl;
	else
		cout << "not found! " << endl;	

	timeStart = clock();		
	c.sort();						
	cout << "c.sort(), milli-seconds : " << (clock()-timeStart) << endl;		
	c.clear();	 
}			
int main()
{
	long int value;
	cout<<"how many elements:";
	cin>>value;
	test_slist(value);
	return 0;
}

 运行一下

 

 与forward_list无异

posted @ 2019-12-09 17:45  C_hp  阅读(874)  评论(0编辑  收藏  举报