Сортировка вектора с указателем на объект C ++ - PullRequest
0 голосов
/ 29 мая 2020

Если кто поможет, буду очень признателен. Как мне отсортировать этот вектор:

vector<Person*>person

по этому критерию:

Surname

Я уже пробовал использовать набор, но он удаляет объект, если существует более 2 объектов с одинаковыми Surname

, есть много строковых переменных, и мне нужно отсортировать его по

Surname

и тогда, если фамилии совпадают, мне нужно отсортировать их по

Name

, а также сортировать по шестнадцатеричному значению этого указателя ... РЕДАКТИРОВАТЬ: Больше кода, как вы просите:

for (pChild = pRoot->FirstChildElement("Member"); pChild != NULL; pChild = pChild->NextSiblingElement())
    {
        string Surname = pChild->Attribute("surname");
        string Name = pChild->Attribute("name");
        string DateOfBirth = pChild->Attribute("dateofbirth");
        person.push_back(new Person(Surname, Name, DateOfBirth));
    }

Ответы [ 4 ]

3 голосов
/ 29 мая 2020

Если вы не покажете больше своего кода, вам будет трудно помочь, но я бы посмотрел документацию для std :: sort () , поскольку вы можете создавать собственные операторы для сортировки вашего вектора.

0 голосов
/ 29 мая 2020

Я немного повеселился, работая с std::set. Есть пара примеров компараторов. Одна функция и один «функтор».

#include <iostream>
#include <set>
#include <string>

struct Person {
  uint64_t id;
  std::string name;
  std::string family_name;

  bool operator<(const Person &other) const {
    if (family_name == other.family_name) {
      if (name == other.name) {
        return id < other.id;
      } else {
        return name < other.name;
      }
    } else {
      return family_name < other.family_name;
    }
  }
};

std::ostream &operator<<(std::ostream &os, const Person &x) {
  return os << '{' << x.id << ", " << x.name << ", " << x.family_name << '}';
}

bool person_ptr_less(const Person *a, const Person *b) { return *a < *b; }

class PersonPtrComparator {
public:
  bool operator()(const Person *a, const Person *b) const { return *a < *b; }
};

int main() {
  std::set<Person *, bool (*)(const Person *, const Person *)> people(
      person_ptr_less);
  people.emplace(new Person{1, "Joe", "Smith"});
  people.emplace(new Person{2, "Joe", "Blow"});
  people.emplace(new Person{3, "Joa", "Smith"});
  people.emplace(new Person{4, "Joe", "Smith"});

  std::set<Person *, PersonPtrComparator> people_2(people.begin(),
                                                   people.end());

  for (const auto &x : people) {
    std::cout << *x << '\n';
  }
  std::cout << "---\n";
  for (const auto &x : people_2) {
    std::cout << *x << '\n';
  }
  return 0;
}
0 голосов
/ 29 мая 2020

Вот полный пример

#include <vector>
#include <iostream>
#include <algorithm>

class Person
{
public:
    std::string s1, s2, s3;

    Person(std::string S1, std::string S2, std::string S3) : s1(S1), s2(S2), s3(S3) {}
};

struct less_than_key
{
    inline bool operator() (const Person* const p1, const Person* const p2)
    {
        if (p1->s1 < p2->s1)
            return true;
        else if (p1->s1 == p2->s1 && p1->s2 < p2->s2)
            return true;

        return false;
    }
};

int main()
{
    std::vector<Person*> persons{ new Person("C", "D", "E"), new Person("C", "C", "D"),
                                  new Person("B", "C", "D"), new Person("B", "C", "E")};

    std::sort(persons.begin(), persons.end(), less_than_key());

    for (auto person : persons)
    {
        std::cout << person->s1 << ' ' << person->s2 << std::endl;
    }

    return 0;
}
0 голосов
/ 29 мая 2020

Вы можете использовать такой компаратор:

// Simple class
class Person {
    public:
     string name;
    Person(string name) {
      this->name = name;
    }
};

// create a comparator like this with two objects as parameters.
bool comparator(Person* a, Person *b) {
  return a->name > b->name;
}

int main() {
  vector<Person* > v;
  v.push_back(new Person("ajay"));
  v.push_back(new Person("tanya"));

  // pass the comparator created into sort function.
  sort(v.begin(), v.end(),comparator);

  // printing output to check
  for(int i=0;i<v.size();i++) {
    cout<<v[i]->name<<endl;
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...