0

セットに問題あり。何が間違っているのかわかりません。多分あなたの誰かが私を助けることができます。それでは始めましょう、私のプログラムの出力は次のようになります:

Iksinski Adam, Kowalski Jan, Nowak Adam, Nowak Jan,

したがって、最初の文字列でソートされます。

そして、ここに私のプログラムがあります:

#include <set>
#include <iterator>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
class Person{
public:
Person(){}
Person(string v , string v1):nazw(v),imie(v1){}
bool operator<(const Person & K) const
{
    return ((this->getN()>K.getN())?0:1);
    //return ((this->getN()<K.getN())?1:0);
}
string getN()const
{
    return nazw;
}
/*
bool operator()(Person & K, Person & K1)
{
    return ((K->getN()<K1.getN())?1:0);
}
*/
friend ostream& operator<<(ostream & o , const Person&K)
{
    o << K.nazw << " " << K.imie;
    return o;
}
private:
string nazw,imie;
};
struct cmp
{
    bool operator()(const Person &K , const Person &K1)
    {
        return ((K.getN()<K.getN())?1:0);
    }
};
int main()
{
//typedef set<Person> kontener_typ;
typedef set<Person,cmp> kontener_typ;
kontener_typ c;
c.insert(Person("Nowak","Jan"));
c.insert(Person("Nowak","Adam"));
c.insert(Person("Kowalski","Jan"));
c.insert(Person("Nowak","Adam"));
c.insert(Person("Iksinski","Adam"));
std::copy (c.begin(), c.end(), ostream_iterator<Person>(cout, " ,"));
std::cout << std::endl;
}

わかりましたので、メインでは typdef とコピー機能しか編集できません(ただし、セットを出力するにはそれを使用する必要があります)。ご覧のとおり、operator< を Person でオーバーロードしようとしましたが (競合する Person を Person に設定したため)、動作しません。ファンクターも試してみましたが、出力は次のようになります

Iksinski Adam ,Nowak Adam ,Kowalski Jan ,Nowak Adam ,Nowak Jan ,

したがって、2 番目の文字列は削除する必要があります。

幸運を :)。

4

2 に答える 2

3

Your code is using your comparator cmp functor object. There is a bug in it:

struct cmp
{
    bool operator()(const Person &K , const Person &K1)
    {
        // one of these _should_ be K1
        return ((K.getN()<K.getN())?1:0);
    }
};

I like to name my variables in a way that it becomes clear how they are being compared, for instance:

struct cmp
{
    bool operator()(const Person &left , const Person &right)
    {
        return left.getN() < right.getN();
    }
};

This clarifies (for me at least) that the operator is comparing like this: left < right.

However, you also need to sort by "first name" as a secondary criteria, which would make the function look like this:

struct cmp
{
    bool operator()(const Person &left , const Person &right)
    {
        if(left.getN() < right.getN())
           return true;
        else if(left.getN() > right.getN())
           return false;
        // assuming the getI() function returns the first name,
        // just as the getN() function returns the last name
        else if(left.getI() < right.getI())  
           return true;
        else
           return false;
    }
};
于 2013-02-14T16:16:01.270 に答える