0

I was trying to learn to use sets that contain a struct, but ran into a strange problem.

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;
};



int main()
{

    Course test_course1 = {"English", "Language", 5};
    Course test_course2 = {"Spanish", "Language", 4};
    Course test_course3 = {"Spanish", "Language", 10};

    set<Course> test_set;

    // This is what causes the issues. If I block the following three lines of code, the program runs perfectly.
    test_set.insert(test_course1);
    test_set.insert(test_course2);
    test_set.insert(test_course3);


    map <string, set<Course>> test_map;
    test_map.insert({"London", test_set});
    test_map.insert({"New York", test_set});
    test_map.insert({"New York", test_set});


    for (auto i: test_map)
    {

        cout << "In  " << i.first << " there are following courses " << endl;

        for (auto x :i.second){
            cout <<x.name << endl;
        }

    }

    return 0;
}

The issue? I've take a screenshot of all the issues that appear if I try to insert the struct Course into a set: the screenshot

P.S. I know that that test_course2 and test_course3 are almost identical. I'm just testing...

8
  • 1
    Screenshots are unreadable. Please paste the error message as text. Commented Oct 18, 2020 at 19:13
  • 1
    A std::set is an ordered structure. However, struct Course has no operator< so std::set does not know how to order the instances of Course. Commented Oct 18, 2020 at 19:18
  • 1
    An std::set of elements, being a binary search tree, requires < for that type of element to be defined, because otherwise it has no idea how to insert them. Commented Oct 18, 2020 at 19:18
  • Alternatively: stackoverflow.com/questions/41648480/… You can't expect the compiler to do magic. A compiler is stupid and it doesn't guess how to sort your struct. Commented Oct 18, 2020 at 19:20
  • @mfnx Could you please code a visual example that would show what it is that should've been done differently? I know what an operator is but in this context I don't quite follow... Commented Oct 18, 2020 at 19:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.