Overloaded the operator for its class. In separate expressions when comparing errors there is no
cout << (StringLocation("123", 123) < StringLocation("123", 124)); // Вывод: 1 But when added to set
map<string, set<StringLocation> > A; A["123"].insert(StringLocation("123", 213)); An error occurs:
no match for 'operator <' (operand types are 'const StringLocation' and 'const StringLocation')
How to designate this comparison operator to be seen by set ?
Code:
#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 :
What if I need to write an operator! = For iterators?
// Такая проверка не работает :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; }