不知何故,我无法使用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<pair<int, string>>
(使用stable_partition相同的代码与拉姆达{回报p.first == _INT;}和它的工作。
会感谢你的帮助
该std::stable_partition
功能应该修改向量。但是,你在呼唤它在const
成员函数,所以storage
是const
那里。这可不行。
解决方法:不要让Print
常量,或std::stable_partition
副本使用storage
。也不是一个很好的解决方案,所以你应该重新考虑你的设计。
您需要定义重载运算符=为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;
};