Ric*_*ard 6 c++ sorting class vector
我正在尝试对包含int和每个元素中的字符串的向量进行排序.它是类型的向量,称为向量配方.得到上述错误,这是我的代码:
在我的Recipe.h文件中
struct Recipe {
public:
string get_cname() const
{
return chef_name;
}
private:
int recipe_id;
string chef_name;
Run Code Online (Sandbox Code Playgroud)
在我的Menu.cpp文件中
void Menu::show() const {
sort(recipes.begin(), recipes.end(), Sort_by_cname());
}
Run Code Online (Sandbox Code Playgroud)
在我的Menu.h文件中
#include <vector>
#include "Recipe.h"
using namespace std;
struct Sort_by_cname
{
bool operator()(const Recipe& a, const Recipe& b)
{
return a.get_cname() < b.get_cname();
}
};
class Menu {
public:
void show() const;
private
vector<Recipe> recipes;
};
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Menu::show()声明const,因此它Menu::recipes被认为已被声明为std::vector<Recipe> const.
显然,排序std::vector<>变异,所以Menu::show()一定不能const(或Menu::recipes必须是mutable,但在这种情况下,这似乎在语义上是不正确的).