I’m trying to sort a vector that contains an int and a string in each element. It is a vector of class type called vector recipes. Getting the above error, here’s my code:
In my Recipe.h file
struct Recipe {
public:
string get_cname() const
{
return chef_name;
}
private:
int recipe_id;
string chef_name;
In my Menu.cpp file
void Menu::show() const {
sort(recipes.begin(), recipes.end(), Sort_by_cname());
}
In my Menu.h file
#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;
};
What am I doing wrong?
Menu::show()is declaredconst, so inside of itMenu::recipesis considered to have been declared asstd::vector<Recipe> const.Obviously, sorting a
std::vector<>mutates it, soMenu::show()must not beconst(orMenu::recipesmust bemutable, but this seems semantically incorrect in this case).