Search code examples
c++error-handlingstdmap

Error in map with 2 classes: "binary '<': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator"


I'm having a weird error while declaring this map:

std::map<LoggedUser, GameData> m_players;

I've looked at many possible solutions, but couldn't find anything that works. I can't find the problem that causes this.

The error:

C2676 binary '<': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator

Game (where the map is declared):

#pragma once

#include "LoggedUser.h"
#include "Question.h"
#include "GameData_struct.h"
#include <vector>
#include <map>

class Game
{
private:
    std::vector<Question> m_questions;
    std::map<LoggedUser, GameData> m_players;

public:
    void add_question(Question question);
    void add_into_m_players(LoggedUser logged_user, GameData game_data);
    Question getQuestionForUser(LoggedUser logged_user);
    bool submitAnswer(LoggedUser logged_user, std::string answer);
    void removePlayer(LoggedUser logged_user);
};

LoggedUser:

#pragma once
#include <string>

class LoggedUser
{
private:
    std::string _m_username;
    int id;
public:
    LoggedUser();
    LoggedUser(std::string username, int id);
    std::string get_username();
    int get_id();
};

GameData:

#pragma once

#include <iostream>
#include <string>
#include "Question.h"

//Game data struct
struct GameData
{
    Question currentQuestion;
    unsigned int correctAnswerCount;
    unsigned int wrongAnswerCount;
    unsigned int averangeAnswerTime;
};

Question:

#pragma once

#include <string>
#include <vector>
//Question 
class Question
{
private:
    std::string m_question;
    std::vector<std::string> m_possibleAnswers;
public:
    std::string getQuestion();
    std::string getPossibleAnswers();
    std::string getCorrentAnswer();
};

Solution

  • std::map is a sorted container. It uses operator< by default to compare keys for sorting and matching (you can optionally specify your own comparitor to override this behavior).

    The error message is complaining that your LoggedUser class does not implement an operator< for comparing the map's keys.