简体   繁体   中英

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.

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.

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