[c++] std::map problem [solved]

Started by
2 comments, last by Zahlman 15 years, 4 months ago
I've read in some tutorials about maps that when you want to use a class in a map and you want to acces the map with an iterator you have to overload the < operator. I've done that and the overloaded operator works. But when I try to compile the program with that class in a map it doesn't work. I get this error:
In function `int main()':|
no match for 'operator<' in 'loop < (&mymap)->std::map<_Key, _Tp, _Compare, _Alloc>::end [with _Key = std::string, _Tp = myclass, _Compare = std::less<std::string>, _Alloc = std::allocator<std::pair<const std::string, myclass> >]()'|
#include <iostream>
#include <map>

using namespace std;

class myclass
{
    public:
    int something;

    bool operator < ( myclass temp)
    {
        return (something<temp.something);
    }

};

int main()
{
    std::map<string, myclass> mymap;

    mymap["apple"].something = 0;
    mymap["banana"].something = 1;
    mymap["cherry"].something = 2;

    if (mymap["apple"] < mymap["banana"])
    {
        cout << "The < operator works." << endl;
    }

    for(map<string, myclass>::iterator loop = mymap.begin() ; loop < mymap.end() ; ++loop)
    {
        cout << loop->second.something << endl;
    }
    return 0;
}

[Edited by - d1rk on December 23, 2008 3:49:08 AM]
Advertisement
loop != mymap.end()
Thanks
Yep. The map *values* have to be order-able (because of how the map works), but the map *iterators* (which are of a data type that you don't define yourself) are not ordered; they can only be compared for equality.

Also, you should pass the argument to your operator< by const reference.

This topic is closed to new replies.

Advertisement