//set的一个使用测试程序:
#include < set >
#include < string >
#include < iostream >
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int arr[3] = { 1, 2, 3 };
set< int > set_test( arr, arr + 3 );
//insert
set_test.insert( 3 ); //3已经存在,插入没有效果
set_test.insert( 4 ); //ok
//find
cout << endl;
set< int >::iterator ite_find = set_test.begin( );
ite_find = set_test.find( 4 );
if ( ite_find != set_test.end( ) )
{
cout << "4 found " << endl;
}
//erases
cout << endl;
int iDelCount = set_test.erase( 4 ); //返回成功删除的个数
if ( iDelCount > 0 )
{
cout << "reased 4" << endl;
}
cout << endl;
cout << "all values: " << endl;
set< int >::iterator ite_loop = set_test.begin( );
for ( ; ite_loop != set_test.end( ); ++ite_loop )
{
cout << *ite_loop << " ";
}
cout << endl;
return 0;
}
以下代码证明set在insert对象时保证对象是有序(默认的有序less<TYPE>,可以改写仿函数类)排放的:
{
// #include <string>
string str1 = "abc"; // string是basic_string<char>,而非C++标准里的string
string str2 = "bcd";
string str3 = "cde";
set<string> set_test;
set_test.insert( str2 );
set_test.insert( str3 );
set_test.insert( str1 );
set<string>::iterator it;
for ( it=set_test.begin(); it != set_test.end(); ++it )
{
cout << *it << endl; // 按字母顺序输出
}
}
以下代码说明如何编写自己的仿函数类型,以实现自定“有序”:
{
set<string*> test_set; // 间接存储
test_set.insert( new string( "cde") );
test_set.insert( new string( "bcd" ) );
test_set.insert( new string( "abc") );
set<string*>::iterator it;
for ( it=test_set.begin(); it != test_set.end(); ++it )
{
cout << **it << endl;
}
cout << " **********" << endl;
// 默认情况下只是使insert进的指针大小有序,不管它指向的string
// 现在写自己的仿函数类来实现自定义的"有序"
struct CompairStringPtr
{
bool operator( )( string const * pStrLeft,
string const * pStrRight ) const
{
return *pStrLeft < *pStrRight; // 字母从小到大为"有序"
}
};
typedef set<string*, CompairStringPtr > StringPtrSet;
StringPtrSet test_set_string_ptr;
test_set_string_ptr.insert( new string( "bcd" ) );
test_set_string_ptr.insert( new string( "cde" ) );
test_set_string_ptr.insert( new string( "abc" ) );
StringPtrSet::iterator it_string_ptr;
for ( it_string_ptr=test_set_string_ptr.begin();
it_string_ptr != test_set_string_ptr.end(); ++it_string_ptr )
{
cout << **it_string_ptr << endl; // 按string有序了
}
}