代码之家  ›  专栏  ›  技术社区  ›  Sergej Fomin

稳定分区问题:没有匹配函数调用“swap”

  •  0
  • Sergej Fomin  · 技术社区  · 6 年前

    不知怎么的,我不能在

    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>> (使用lambda返回p.first=_int;的稳定_分区,它起作用。

    谢谢你的帮助

    2 回复  |  直到 6 年前
        1
  •  3
  •   Max Langhof    6 年前

    这个 std::stable_partition 函数应该修改向量。但是,您在 const 成员函数,所以 storage 康斯特 那里。这不行。

    解决方案:不要 Print 使用或使用 std::稳定分区 在副本上 存储 . 两者都不是一个很好的解决方案,所以您应该重新考虑您的设计。

        2
  •  1
  •   Loc Tran    6 年前

    您还需要为日期类定义overloading operator=如果你做那件事就行了。

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