2

Перегрузил оператор для своего класса. В отдельных выражениях при сравнении ошибок нет

cout << (StringLocation("123", 123) < StringLocation("123", 124)); // Вывод: 1

Но при добавлении в set

map<string, set<StringLocation> > A;
A["123"].insert(StringLocation("123", 213));

Возникает ошибка:

no match for 'operator<' (operand types are 'const StringLocation' and 'const StringLocation')

Как обозначить этот оператор сравнения, чтобы его видел set?

Код:

#include <iostream>
#include <map>
#include <set>

using namespace std;

class StringLocation {
private:
    std::string FileName;   // Имя файла
    int lineOfLocation;     // Номер строки
public:
    StringLocation(std::string FileName_, int lineOfLocation_)
    {
        this->FileName = FileName_;
        this->lineOfLocation = lineOfLocation_;
    }
    std::string getFileName ()
    {
        return this->FileName;
    }
    int getLineOfLocation ()
    {
        return this->lineOfLocation;
    }
    /*
     *  Перегрузка оператора сравнения
     */
    bool operator < (const StringLocation& my_StringLocation)
    {
        if(this->FileName == my_StringLocation.FileName)
            return this->lineOfLocation < my_StringLocation.lineOfLocation;

        return this->FileName < my_StringLocation.FileName;
    }
    /*
     *  Перегрузка ввода/вывода
     *
     *  Выполняется только в том случае, если в основном файле
     *  подключена библиотека <iostream>
     *
     *  _GLIBCXX_IOSTREAM в MinGW
     *  _IOSTREAM_        в MSCVS
     */
    #if defined(_GLIBCXX_IOSTREAM) || defined(_IOSTREAM_)
        friend std::ostream& operator << (std::ostream &out, const StringLocation& my_StringLocation)
        {
            out << "Line " << my_StringLocation.lineOfLocation << ": " << my_StringLocation.FileName;
            return out;
        }
    #endif
};

int main()
{
    map<string, set<StringLocation> > A;

    A["123"].insert(StringLocation("123", 213));
}

UPD:

Как быть, если нужно написать оператор != для итераторов?

// Такая проверка не работает :C
bool operator != (const StringLocation& my_StringLocation) const
{
    return this->FileName != my_StringLocation.FileName && this->lineOfLocation != my_StringLocation.lineOfLocation;
}

std::set<StringLocation> get_info_about_word (std::string word)
{
    auto it = this->invertedIndex[word];
    if(it != this->invertedIndex.end()) // Сравнение!
        return it;
}

1 ответ 1

5

Сделайте его константным:

bool operator < (const StringLocation& my_StringLocation) const

А то получается, что ваш оператор сравнения пытается изменять сравниваемый объект :) А set "на энто пойтить не может" (с) :)

7
  • Проблема решена 3 авг 2017 в 11:21
  • Можете посмотреть дополнение к вопросу? 3 авг 2017 в 12:44
  • invertedIndex - это что? У вас в классе такого вроде нет.
    – Harry
    3 авг 2017 в 12:52
  • invertedIndex - поле другого класса. this->invertedIndex возвращает map<string, set<StringLocation> > 3 авг 2017 в 12:56
  • error: no match for 'operator!=' (operand types are 'std::set<StringLocation>' and 'std::map<std::__cxx11::basic_string<char>, std::set<StringLocation> >::iterator {aka std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, std::set<StringLocation> > >}')| 3 авг 2017 в 12:57

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.