开发者

Help understanding class example code for C++, templates, operator()

I'm not sure exactly what the following class does that we have for a class example. In the following code, what does the operator() do in this case? I don't quite get the *(begin + first) and pretty much the whole return expression as what is being evaluated. Any help would be great. Thanks!

// IndexCompare.h - interface for IndexCompare class template
#ifndef _INDEXCOMPARE_H_
#d开发者_如何学Pythonefine _INDEXCOMPARE_H_
#pragma once

template <class random_iterator>
class IndexCompare {
public:
    IndexCompare(random_iterator begin, random_iterator end)
        : begin(begin), end(end) {}

    ~IndexCompare() {}

    bool operator() (unsigned int first, unsigned int second) {
            return (*(begin + first) < *(begin + second));

    }

private:
    random_iterator begin;
    random_iterator end;
};

#endif


If you're asking what operator () does, it allows you to call the object like a function. See this article for an example.

If you're asking what the function in your example is doing, it's comparing the values of two elements specified by the indices passed to the function. begin + first refers to the element at index first starting from the iterator begin, similarly begin + second. *(begin + first) gets the value at that location.

You can use this class with any STL container (that supports random access) by passing in a pair of iterators. For example, you could use it with a vector like this:

vector<int> vec;
/* add some elements here */
IndexCompare<vector<int>::iterator> compare(vec.begin(), vec.end());

Now calling compare(2, 5) for example would compare the values of vec[2] and vec[5].


begin is a iterator (think pointer), so begin + first advances to position of first. or in the second case, to position of second. however, it does not modify begin itself.

* is a dereference operator, which essentially gets value being pointed to


The operator() is basically defining functionality for '()' with respect to your class. So in this case, if we had and IndexCompare instance named 'ic', we could write 'ic()' and the defined functionality would be run, similar to a function call and definition.

I hope that helps to understand the operator extension.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜