Advice on a better way to extend C++ STL container with user-defined methods

后端 未结 8 1566
星月不相逢
星月不相逢 2020-12-01 08:41

I inherited from C++ STL container and add my own methods to it. The rationale was such that to the clients, it will look act a regular list, yet has application-specific me

8条回答
  •  天命终不由人
    2020-12-01 09:21

    Since you can only "extend" the vector by using its public interface, it is far more useful to write functions which operate on a vector instead of being part of a vector.

    Heck, if you plan it well, make it work with iterators instead of indexes and it'll work with more than just std::vector (see for some very good examples).

    For example, you could use a functor for the MaxA like this:

    struct CmpA {
        bool operator()(const Item &item1, const Item &item2) { return item1.a < item2.a; }
    }
    
    const int result = std::max_element(v.begin(), v.end(), CmpA()).a;
    

    your specialB could be just as simple with a functor and std::accumulate

    EDIT: or for c++11 and later, it can be as simple as:

    const int result = std::max_element(v.begin(), v.end(), [](const Item &item1, const Item &item2) {
        return item1.a < item2.a;
    }).a;
    

    EDIT: you've asked why it is better to do it this way:

    if you use algorithms, templates and iterators, it'll work even if you decide to put the items in a std::list or whatever. It is simply more versitile and helps code reuseablity.

    Plus the functions in do much of this for you so you can just use little 3 line adapter functors.

    EDIT: In addition to this, tgamblin listed some very compelling reasons to not inherit from std::vector (and most other std containers, including std::string).

提交回复
热议问题