错误是怎么来的?

我写下这样的代码:

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);
}