Error C2678: binary '=': operator not found that accepts a left operand of type 'const Recipe' (or not an acceptable conversion)

I am trying to sort a vector containing an int and a string in each element. This is a class type vector called vector recipes. Getting the above error, here is 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?

+6
source share
2 answers

Menu::show() declared const , so inside it, Menu::recipes is considered declared as std::vector<Recipe> const .

Obviously, sorting a std::vector<> mutates it, so Menu::show() should not be const (or Menu::recipes should be mutable , but in this case it is semantically incorrect).

+6
source

You marked your show method as const , which is not true because it changes the vector of recipes. When I compile the code that you described with gnu gcc 4.2.1, the error is due to the disqualification of the const qualifier, and not the error message.

You can tag your vector with the mutable keyword, but I suspect that this is not what you really want? Marking the vector mutable, it ignores the constant that the compiler usually applies to the vector Menu::show() const vector, and it changes every time Menu :: show () is called. If you really want to use a vector, rather than an ordered set like the others, you can add a dirty state flag to let your program know when it should resort or not.

The following code, which I compile by changing the vector to mutable, to show you the difference, but I still recommend that you do not use sorting using the show show method.

 #include <vector> #include <string> using namespace std; struct Recipe { public: string get_cname() const { return chef_name; } private: int recipe_id; string chef_name; }; class Menu { public: void show() const; private: mutable vector<Recipe> recipes; }; struct Sort_by_cname { bool operator()(const Recipe& a, const Recipe& b) { return a.get_cname() < b.get_cname(); } }; void Menu::show() const { sort(recipes.begin(), recipes.end(), Sort_by_cname()); } 
0
source

Source: https://habr.com/ru/post/899501/


All Articles