Couldn't find a concise answer to this problem.
I have a struct named Course, which consists of three variables. The struct is then inserted into a map, whose key is a place (string). Once the courses are inserted into a map, I want to iterate through the courses and see, if a new course that I am adding is the same apart from the number of enrollments. If it is the same, I want to update the enrollments variable to a new one. However, this is not possible, because I need to use address-of operator (&) in the loop, but once I try to do so a semantic issue is confronted:
error: binding value of type 'const Course' to reference to type 'Course' drops 'const' qualifier stl_set.h:344:7: note: selected 'begin' function with iterator type 'std::set<Course, std::less, >std::allocator >::iterator' (aka '_Rb_tree_const_iterator')
Here is the code:
#include <cstring>
#include <iostream>
#include <string>
#include <map>
#include <set>
using namespace std;
struct Course
{
string name;
string theme;
int enrollments;
};
bool operator <(const Course& lhs, const Course& rhs)
{
return ((lhs.name <= rhs.name) );
}
int main()
{
Course test_course1 = {"English", "Language", 5};
Course test_course2 = {"Armenian", "Language", 10};
Course test_new_course = {"Armenian", "Language", 15};
set<Course> test_set;
test_set.insert(test_course1);
test_set.insert(test_course2);
map <string, set<Course>> courses;
courses.insert({"New York", test_set});
string location = "New York";
for (Course& course: courses.at(location))
{
if ((course.theme == test_new_course.theme) && (course.name == test_new_course.name))
{
course.enrollments = test_new_course.enrollments;
}
}
return 0;
}
Apparently this is to do with the operator <
but what should I do with it in order to make this work?
I have a bonus question: is there a way to make the operator <
tell set to put courses first based on theme (alphabetical order) and then based on course name? I tried to achieve this with a && (lhs.theme < rhs.theme)
but nothing good came out of it.
Thanks in advance.