开发者

Comparison of custom objects and operator overloading in C++

Rea开发者_运维问答d this question about how to compare custom objects in C++. I did not understand the operator overloading used here. What is the operator being overloaded here? Is it ()? What is the use of overloading that?

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};

struct less_than_key
{
    inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
    {
        return (struct1.key < struct2.key);
    }
};


The point is to use a less_than_key object as a function:

less_than_key f;
bool result = f(key1, key2);

Object that can be called like functions (including garden variety functions) are sometimes called functors (warning: this is not the meaning of functor in mathematics), or function objects, or sometimes functoids.

Many standard library algorithms and containers expect such function objects as arguments. For instance, std::map can be customized with a binary function object (exactly like the one you showed us) to know how it should sort the keys.

Please refer to this beginners' book list and read about standard algorithms and containers to understand where you can use those beasts.

Function objects and iterators are the core of the C++ standard library, you should really learn about them to make the best use of C++.


The operator() is a function call operator with, probably, the most common use being to allow you to use normal function call syntax on an object that could be considered as behaving in a 'function-like' way.

In this example, you can call less_than_key() which is used by the STL sort.


This is called functor. This is used heavily in C++ apis. Some of these apis take a functor which performs object specific operations.

Example pseudo code:

- Sorting a list of MyStruct objects.

sort api in algorithm.
std::list<MyStruct> mystructlist;
// populate mystructlist
sort(mystructlist.begin(), mystructlist.end(), less_than_key);


It is often called the "functor" operator and it is useful because it mimics the syntax of a call to a regular function.

Objects with such an overloaded operator are often used with stlalgorithms like std::find_if() or in your case, std::sort().

Here are some samples:

std::vector<MyStruct> myvector;

less_than_key comparator;
std::sort(myvector.begin(), myvector.end(), comparator);

Or:

MyStruct a, b;
less_than_key comparator;

if (comparator(a, b))
  // Do something
else
  // Do something else.

As you can see, there is not syntax difference between calling the operator() method of an instance of less_than_key and calling a function with the same prototype (well, disregarding of the hidden this parameter).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜