0

I have the following code, I've got some errors like:

struct duplicatedTurns
    {
        int nodeId;
        int min;
        int max;

        bool operator==(const duplicatedTurns& other) const
        {
            return nodeId == other.nodeId && min == other.min && max == other.max;
        }

I solved it here to following code:
bool operator<(const duplicatedTurns& other) const
{
if (nodeId != other.nodeId) return nodeId < other.nodeId;
if (min != other.min) return min < other.min;
if (max != other.max) return max < other.max;
return false;
}

    };

The container that I want to use:

std::map<duplicatedTurns, int> selected;

After i would like to insert elements there:

selected.insert(duplicatedturns{it->nodeId, std::min(it->toLinkId, it->fromLinkId), std::max(it->toLinkId, it->fromLinkId)}, "here: increment the number if the key are the same" );

2 Answers2

1

How can I use struct as key in a std::map?

Either by making the class less-than comparable using the default comparison function of std::map which is std::less (this can be achieved by defining overload for operator< which satisfies the specified requirements), or by providing a custom comparison function as a template argument for std::map.

eerorika
  • 223,800
  • 12
  • 181
  • 301
0

In C++ Map is ordered by default. That's why operator< has to be defined, so it could sort elements.