首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

问一个关于模板的有关问题

2012-04-07 
问一个关于模板的问题为了保存一份不相同的字符串表,我们可以使用以下数据结构(在实际的情况中,它并非最优

问一个关于模板的问题
为了保存一份不相同的字符串表,我们可以使用以下数据结构(在实际的情况中,它并非最优案):
std::set<std::wstring> MyStringTable;
如果现在的需求是,在比较字符串时不区分大小写,请写出如何修改以上的定义。提示,set类的模版参数为:
template<class _Key, class _Pr = less<_Key>, class _Al = allocator<_Key> >
class set;


[解决办法]

C/C++ code
#include <iostream>#include <set>#include <string>using namespace std;template<class CH=char>struct NocaseCompare{    typedef basic_string<CH> Str;    typedef typename Str::const_iterator IT;    bool operator()(const Str& ls, const Str& rs)    {       IT pl=ls.begin();       IT pr =rs.begin();       while(pl!=ls.end() && pr!=rs.end() && toupper(*pl) ==toupper(*pr))       {           ++pl;           ++pr;       }       if(pl==ls.end())return pl!=rs.end();       if(pr!=rs.end())return false;       return toupper(*pl) <toupper(*pr);    }};void main(){  set<wstring, NocaseCompare<wchar_t> > sets;  set<string, NocaseCompare<char> > csets;}
[解决办法]
C/C++ code
#include <iostream>#include <set>#include <string>using namespace std;template<class CH=char>struct NocaseCompare{    typedef basic_string<CH> Str;    typedef typename Str::const_iterator IT;    bool operator()(const Str& ls, const Str& rs)    {       IT pl=ls.begin();       IT pr =rs.begin();       while(pl!=ls.end() && pr!=rs.end() && toupper(*pl) ==toupper(*pr))       {           ++pl;           ++pr;       }       if(pl==ls.end())return pl!=rs.end();       if(pr!=rs.end())return false;       return toupper(*pl) <toupper(*pr);    }};void main(){  set<wstring, NocaseCompare<wchar_t> > sets;  set<string, NocaseCompare<char> > csets;}
[解决办法]
#include <string>
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <iterator>
#include <set>
//---------------------------------------
using namespace std;
template <class T>
struct less_str : public binary_function<T, T, bool>
{
bool operator()(const T& t1, const T& t2)
{
T t3 = t1;
T t4 = t2;
transform(t1.begin(), t1.end(), t3.begin(), toupper);
transform(t2.begin(), t2.end(), t4.begin(), toupper);
if (t3 < t4)
{
return true;
}
return false;
}
};
int main(int argc, char* argv[])
{
string str1 = "sss";
string str2 = "SSs";
set<string, less_str<string> > ustr;
ustr.insert(str2);
ustr.insert(str1);
cout << ustr.size() << endl;
copy(ustr.begin(), ustr.end(), ostream_iterator<string, char>(cout, ","));
system("pause");
return 0;
}
//---------------------------------------
[code=C/C++][/code]

热点排行