2

I've had several programs I made in which the compiler didn't flag any errors when I wrote std::set with my own objects but as soon as I attempted to build the program I got some error that seemed to be pointing to some implementation file for std::set. For example, in my program right now the compiler is pointing to the line

struct _LIBCPP_TYPE_VIS_ONLY less : binary_function<_Tp, _Tp, bool>
{
    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY 
    bool operator()(const _Tp& __x, const _Tp& __y) const
        {return __x < __y;} // <---- That's the problem line
};

with the error

Invalid operands to binary expression ('const XMLNode' and 'const XMLNode')

and that traces back to the line

std::set<XMLNode> children;

in my code. Is my assumption correct that the program is confused because it doesn't know how to compare XMLNode elements? If so, what is a data structure I can use similar to std::set except that it's equipped to hold any type of element? I want something that holds objects of the same type without any repeats and preferably with fast access.

2
  • The whole point of writing your own comparison functor is that your code should know how to make a meaningful comparison between two objects. You could try unordered_set but for that you need to write a hashing function. Dec 8, 2014 at 22:39
  • It is saying that you need to implement the less than (<) operator for your class, or provide an object that can carry out the comparison - a functor
    – smac89
    Dec 8, 2014 at 22:46

1 Answer 1

2

Trees (the underlying structure of a set) rely on being able to compare objects so as to decide in which branch to insert them and, in the end, provide O(log n) accesses.

Therefore, if you want to use std::set, your type needs to provide a way to compare objects - either through operator <, an implementation of std::less<XMLNode>, or by passing your comparer when declaring the set through Compare, its first template argument.

If the concept of comparison does not apply to XMLNode, then you may be interested in either making up an artificial comparison criterion, or using std::unordered_set (which offers amortized O(1) accesses) and providing an implementation for std::hash<XMLNode>.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.