How to split a vector into n "almost equal" parts

Viewed 18437

I have a problem that I would like to merge a large number of images using ImageMagick's convert.exe, but under Windows I have a 8192 byte long command line limit.

My solution to this is to split the task into smaller sub-task, run them, and do a final task which combines them together.

My idea is to write a function, which takes a vector of images and an integer, and splits the vector into n sub-vector all having "almost equal" parts.

So for example if I would like to split 11 into 3 groups it would be 4-4-3.

Can you tell me how can I do it in C++? I mean, to write a function

split_vec( const vector<image> &images, int split )

which does the splitting?

Also, can you tell me what is the most efficient way to do if I don't need to create new vectors, just iterate through the sub-parts? Like the std::substr function with std::string?

Note: I already use Boost in the project, so if there is some nice tool in Boost for this then it's perfect for me.

8 Answers

This is how I do it (I know it's very similar to the answer but that was my actual code lol):

template<typename T>
std::vector<std::vector<T>> splitVector(const std::vector<T>& vec, size_t n)
{
    std::vector<std::vector<T>> out_vec;
    size_t length = vec.size() / n;
    size_t remain = vec.size() % n;
    size_t begin = 0;
    size_t end = 0;

    for (size_t i = 0; i < n; ++i)
    {
        end += length + (i < remain);
        out_vec.emplace_back(vec.begin() + begin, vec.begin() + end);
        begin = end;
    }

    return out_vec;
}

You could also return pair of iterators or such if you don't like copying.

Related