简体   繁体   中英

C++ callback v.s. vector return in a data structure traversal method?

In the following example, I've implemented two ways of traversing a data structure. One uses a result vector which implies copies while the other uses a callback.

Which of the two approaches is usually better to use in typical C++ applications? Said differently, does one solution have flaws/drawbacks?

#include <iostream>
#include <vector>
#include <functional>

using namespace std;

template<typename T>
class Foo {
    vector<T> v;

    vector<T> query(T query) {
        vector<T> results;
        for (auto &k : v)
            if (match(query, k))
                results.push_back(k);
    }

    void query(T query, const std::function<void(T&)>&cb) {
        for (auto &k : v)
            if (match(query, k))
                cb(k);
    }
};

template<typename T>
void display(Foo<T> &foo, T &query) {
    for(auto el : foo.query(query))
       cout << el << endl;

    foo.query(query, [](T &el) {
        cout << el << endl;
    });
}

In this case I would use the callback approach, but I would remove the std::function and replace it with a template type. std::function uses type erasure and that requires dynamic allocation and a little bit of overhead. A function template like

template<typename Callback>
void query(T query, const Callback& cb) {
    for (auto &k : v)
        if (match(query, k))
            cb(k);
}

will remove that overhead and still let you pass any function object you want to the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM