关于list的sort()中自己写的比较函数
编一个程序对一个list中的字符串进行按字典序的排序
#pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Nocase{
public:
bool operator()(const string& x,const string& y) const
{
string::const_iterator p=x.begin();
string::const_iterator q=y.begin();
while(p!=x.end()&&q!=y.end()&&toupper(*p)==toupper(*q)){
p++;q++;
}
if (x==x.end()) return q!=y.end();
return toupper(*p)<toupper(*q);
}
};
//在比较字符串时忽略大小写,即按字典序
void main()
{
list<string> strlist;
//在strlist中存n个字符串
strlist.sort(Nocase());是这么用的吗??????
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
list<string>::iterator p;
for (p=strlist.begin(); p!=strlist.end();p++)
fout<<(*p)<<endl;
}
问题点数:25、回复次数:7Top
1 楼kingarrive(安德烈·帝雷)回复于 2003-09-01 00:40:21 得分 0
为何程序说我出错???请各位前辈指点Top
2 楼oopig(面向对象的猪)回复于 2003-09-01 02:12:27 得分 5
你应该实现以下模版类的特化(升序或者降序)。vc6可能有些问题,dev-c++下可以编译通过
template<class Type>
struct less : public binary_function <Type, Type, bool>
{
bool operator()(
const Type& _Left,
const Type& _Right
) const;
};
template<class Type>
struct greater : public binary_function <Type, Type, bool>
{
bool operator()(
const Type& _Left,
const Type& _Right
) const;
};
Top
3 楼goodboy1881(积木)(谁都别拦着我在水源升星)回复于 2003-09-01 08:47:52 得分 10
template <class T, class Allocator>
template<class Compare> void list<T, Allocator>::sort (Compare comp)
{
for (int n = 1; n < size(); n *= 2) {
iterator i1 = begin(), i2 = begin(), i3 = begin();
__advance(i2, (difference_type) n, end());
__advance(i3, (difference_type) (2*n), end());
for (int m = 0; m < (size()+(2*n))/(n*2); m++) {
if (i1 != end() && i2 != end()) {
__adjacent_merge(i1, i2, i3, comp);
i1 = i3;
i2 = i3;
__advance(i2, (difference_type) n, end());
__advance(i3, (difference_type) 2*n, end());
}
}
}
}
嘿嘿,看代码吧,可见你的调用是正常的,没有错误的Top
4 楼kingarrive(安德烈·帝雷)回复于 2003-09-01 08:58:44 得分 0
那在VC6下有什么方法解决吗?Top
5 楼goodboy1881(积木)(谁都别拦着我在水源升星)回复于 2003-09-01 11:53:44 得分 2
写标准STL代码就不要用VC了,就用borland C++ complier就行了
VC6出来的时候一些新的C++特性还没有呢
所以vc对C++支持的不好Top
6 楼kingarrive(安德烈·帝雷)回复于 2003-09-01 16:58:36 得分 0
是BC 31还是BCB?各位能不能提供一些好点的编译器呢?最好能给出下载地址。
多谢了!!Top
7 楼atEleven(@十一)回复于 2003-09-01 21:14:47 得分 8
vc6的确不支持 strlist.sort(Nocase()); 这句.
我把下面的程序在vc.net2003 打开编译就完全得到正确的答案了.
#pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Nocase{
public:
Nocase(){};
bool operator()(const string& x,const string& y) const
{
string::const_iterator p=x.begin();
string::const_iterator q=y.begin();
while(p!=x.end()&&q!=y.end()&&toupper(*p)==toupper(*q)){
p++;q++;
}
if (p==x.end()) return q!=y.end();
return toupper(*p)<toupper(*q);
}
};
//在比较字符串时忽略大小写,即按字典序
void main()
{
list<string> strlist;
//在strlist中存n个字符串
strlist.push_back ("sdf");
strlist.push_back ("ADf");
strlist.sort(Nocase());
list<string>::iterator p;
for (p=strlist.begin(); p!=strlist.end();p++)
cout<<(*p)<<endl;
}Top



