A.B.
A.B.

Reputation: 16630

Declaring a function that takes generic input and output iterators

I would like to modify this function so that mimics standard library algorithms by taking input iterators and writing to an output iterator instead of what it's currently doing.

Here is the code:

template <class T>
std::vector<std::vector<T>> find_combinations(std::vector<std::vector<T>> v) {
    unsigned int n = 1;
    for_each(v.begin(), v.end(), [&](std::vector<T> &a){ n *= a.size(); });
    std::vector<std::vector<T>> combinations(n, std::vector<T>(v.size()));
    for (unsigned int i = 1; i <= n; ++i) {
        unsigned int rate = n;
        for (unsigned int j = 0; j != v.size(); ++j) {
            combinations[i-1][j] = v[j].front();
            rate /= v[j].size();
            if (i % rate == 0) std::rotate(v[j].begin(), v[j].begin() + 1, v[j].end());
        }
    }
    return combinations;
}

How it's used:

std::vector<std::vector<int>> input = { { 1, 3 }, { 6, 8 } };
std::vector<std::vector<int>> result = find_combinations(input);

My problem is writing the declaration. I'm assuming that it involves iterator traits but I haven't been able to figure out the syntax.

Upvotes: 1

Views: 220

Answers (1)

Yochai Timmer
Yochai Timmer

Reputation: 49221

First of all, don't pass vectors by value. A return value may be optimized and moved (even if it's nor c++11) , as an input parameter it's hard for the compiler to know if it can just pass a reference.

Second, you can't initialize a vector of vectors like that.

Now, for the syntax, just use:

std::vector<std::vector<T>> find_combinations(std::vector<std::vector<T>>& v) {

}

It will work fine.

Upvotes: 1

Related Questions