【问题标题】:STABLE_PARTITION problems: no matching function to call to "swap"STABLE_PARTITION 问题:没有匹配的函数来调用“交换”
【发布时间】:2019-02-11 10:58:09
【问题描述】:

不知何故我无法在

上使用 stable_partition 算法
vector<pair<Class, string>>. 

我可以重新组织代码以获得我想要的东西,但对我来说(因为我是 C++ 新手)更多的是“为什么”而不是“如何”的问题。如果您澄清这种行为会很高兴:

首先,类Date(可以省略,以后再看):

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

};

编译时会返回很多同类问题:

我在 vector&lt;pair&lt;int, string&gt;&gt; 上尝试过相同的代码(使用 stable_partition 和 lambda {return p.first == _int; } 并且成功了。

感谢您的帮助

【问题讨论】:

  • 您能粘贴控制台选项卡中的编译输出吗?
  • 最大,很大。
  • 您是否要按日期对事件进行排序? Database 可能更容易拥有 std::multi_map&lt;Date, std::string&gt; storage; 而不是它现在拥有的两个数据成员。
  • @caleth,thanx,我正在通过在线课程学习 C++,我们还没有学习 multi_map。

标签: c++ iterator bidirectional


【解决方案1】:

std::stable_partition 函数应该修改向量。但是,您在 const 成员函数中调用它,所以 storageconst 那里。这行不通。

解决方案:不要将Print 设为常量,或在storage 的副本上使用std::stable_partition。两者都不是一个很好的解决方案,因此您可能应该重新考虑您的设计。

【讨论】:

  • 在类定义中将 storage 指定为(同样不具吸引力)mutable
【解决方案2】:

您还需要为 Date 类定义重载 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;
};

【讨论】:

    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多