Проблемы STABLE_PARTITION: нет подходящей функции для вызова "swap" - PullRequest
0 голосов
/ 11 февраля 2019

почему-то я не могу использовать алгоритм stable_partition на

vector<pair<Class, string>>. 

Я могу реорганизовать код, чтобы получить то, что я хочу, но для меня (поскольку я новичок в C ++) это больше "ПОЧЕМУ"а не "КАК" вопрос.будет рад, если вы уточнить это поведение:

Во-первых, класс Дата (вы можете опустить его и посмотреть на него позже):

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <vector>

using namespace std;

class Date {
public:
    Date(int new_year, int new_month, int new_day) {
        year = new_year;    month = new_month;      day = new_day;
      }

    int GetYear() const {return year;}
    int GetMonth() const {return month;}
    int GetDay() const {return day;}

private:
  int year, month, day;
};

bool operator<(const Date& lhs, const Date& rhs) {
  return vector<int>{lhs.GetYear(), lhs.GetMonth(), lhs.GetDay()} <
      vector<int>{rhs.GetYear(), rhs.GetMonth(), rhs.GetDay()};
}

bool operator==(const Date& lhs, const Date& rhs) {
  return vector<int>{lhs.GetYear(), lhs.GetMonth(), lhs.GetDay()} ==
      vector<int>{rhs.GetYear(), rhs.GetMonth(), rhs.GetDay()};
}

ТАК ЭТО КЛАСС С ПРОБЛЕМОЙ:

class Database {
public:
    void Add(const Date& date, const string event){
            storage.push_back(make_pair(date, event));
            set_dates.insert(date);

    }


    void Print(ostream& s) const{

        for(const auto& date : set_dates) {
// TROUBLE IS HERE:
            auto it = stable_partition(begin(storage), end(storage),
                [date](const pair<Date, string> p){
                return p.first == date;
            });

        };

}

private:
      vector<pair<Date, string>> storage;
      set<Date> set_dates;

};

При компиляции возвращает много проблем одного вида: enter image description here

Я пробовал тот же код на vector<pair<int, string>> (использовалстабильное разделение с лямбда {return p.first == _int;}, и это сработало.

Буду признателен за вашу помощь

Ответы [ 2 ]

0 голосов
/ 11 февраля 2019

Функция std::stable_partition предназначена для изменения вектора.Однако вы вызываете его в const функции-члене, поэтому storage там const.Это не может работать.

Решение: не делайте Print const или используйте std::stable_partition для копии storage.Это не лучшее решение, поэтому вам, вероятно, следует переосмыслить свой дизайн.

0 голосов
/ 11 февраля 2019

Вам также необходимо определить оператор перегрузки = для класса Date.Это сработает, если вы сделаете это.

class Date {
public:
Date(int new_year, int new_month, int new_day) {
    year = new_year;    month = new_month;      day = new_day;
  }

// Need to define overloading operator=
Date& operator=(const Date& rhs)
{

}

int GetYear() const {return year;}
int GetMonth() const {return month;}
int GetDay() const {return day;}

private:
  int year, month, day;
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...