C++之Effective STL学习笔记Item20

 Q:假设我们现在需要一个string*的set,我们向其插入一些动物到这个set中:

set<string*> ssp;                                                               // ssp = “set of string ptrs”
ssp.insert(new string("Anteater"));
ssp.insert(new string("Wombat"));
ssp.insert(new string("Lemur"));
ssp.insert(new string("Penguin"));

You then write the following code to print the contents of the set, expecting the strings to come out in alphabetical order. After all, sets keep their contents sorted.

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

真正打印出来的会是字符串的指针值。或许你说那我在i前面加个*,取出字符串不就搞定了,so easy!是可以,但是别忘了我们的需求,我们需要使得字符串有序排列,而这样得到的只是对指针值有序排列了,显然不满足我们得要求!

其实我们上述的语句set<string*> ssp;是下面语句的简化写法:

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

If you want the string* pointers to be stored in the set in an order determined by the string values, you can’t use the default comparison functor class less<string*>. You must instead write your own comparison functor class, one whose objects take string* pointers and order them by the values of the strings they point to. Like this:

复制代码
struct StringPtrLess:
    public binary_function<const string*, const string*, bool> {
        bool operator()(const string *ps1, const string *ps2) const
        {
            return *ps1 < *ps2;
        }
};
复制代码

 Then you can use StringPtrLess as ssp’s comparison type:

typedef set<string*, StringPtrLess> StringPtrSet;
    StringPtrSet ssp;

好了,最终的解决方案出炉了:

复制代码
typedef set<string*, StringPtrLess> StringPtrSet;
StringPtrSet ssp;
ssp.insert(new string("Anteater"));
ssp.insert(new string("Wombat"));
ssp.insert(new string("Lemur"));
ssp.insert(new string("Penguin"));
for (auto i : ssp)
{
    cout << *i << endl;
}
复制代码

当然,其中的打印过程可以有很多花样,比如我也可以利用alogrithm来完成,也是OK的。

If you want to use an algorithm instead, you could write a function that knows how to dereference string* pointers before printing them, then use that function in conjunction with for_each:

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

for_each(ssp.begin(), ssp.end(), print);

 感谢大家的阅读,希望能帮到大家!

 Published by Windows Live Writer.

posted @   薛定谔の喵  阅读(682)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示