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;
});
}