为包含指针的关联容器指定比较类型

本文探讨了使用C++标准库set容器时遇到的问题,即当set中存储string指针时,如何正确实现自定义排序逻辑。通过创建自定义比较器,实现了按字符串内容而非指针地址排序的目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误是怎么来的?

我写下这样的代码:

    set<string*> ssp;
    ssp.insert(new string("Ant"));
    ssp.insert(new string("Wom"));
    ssp.insert(new string("Lem"));
    ssp.insert(new string("Pen"));
    for (set<string*>::const_iterator i = ssp.begin(); i != ssp.end(); ++i)
        cout << *i << endl;

当然,循环可以写成这样:

    for (auto i : ssp)
        cout << *i << endl;

我们期望输出Ant, Lem,Pen,Wom,但是输出的是:

0035A020
0035A060
0035A0A0
0035A0E0
请按任意键继续. . .

输出的是指针,指针是按照大小来排序的。

一怒之下,你又解引用一次:

for (set<string*>::const_iterator i = ssp.begin(); i != ssp.end(); ++i)
        cout << **i << endl;

结果是:

0029A020
0029A060
0029A0A0
0029A0E0
Ant
Wom
Lem
Pen
请按任意键继续. . .

并不是有序的。。。。。是不是哪里做错了。。。。。。

哪里错了?

 set<string*> ssp;

实际上是如下形式:

 set<string*, less<string*>> ssp;

要想达到目的,就不应该使用默认的比较函数,必须重新编写比较函数的子类,该类对象以string*为参数,按照他们指向的string进行排序。

应该怎么办?

class stringPtrLess :public binary_function < const string*, const string*, bool >
{
public:
    bool operator()(const string* ps1, const string* ps2) const
    {
        return *ps1 < *ps2;
    }
};

int main()
{
    set<string*, stringPtrLess> ssp;
    ssp.insert(new string("Ant"));
    ssp.insert(new string("Wom"));
    ssp.insert(new string("Lem"));
    ssp.insert(new string("Pen"));
    for (set<string*>::const_iterator i = ssp.begin(); i != ssp.end(); ++i)
        cout << *i << endl;

    for (set<string*>::const_iterator i = ssp.begin(); i != ssp.end(); ++i)
        cout << **i << endl;

}

结果如下:

0030A020
0030A0A0
0030A0E0
0030A060
Ant
Lem
Pen
Wom
请按任意键继续. . .

输出可不可以更优雅一些?

void print(const string *ps)
{
    cout << *ps << endl;
}

int main()
{
    set<string*, stringPtrLess> ssp;
    ssp.insert(new string("Ant"));
    ssp.insert(new string("Wom"));
    ssp.insert(new string("Lem"));
    ssp.insert(new string("Pen"));

    for_each(ssp.begin(), ssp.end(), print);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值