Jump to content
  • Advertisement
Sign in to follow this  
d1rk

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

This topic is 3523 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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]

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!