How to split a vector into n “almost equal” parts

后端 未结 7 615
野性不改
野性不改 2020-12-18 20:03

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.

7条回答
  •  醉梦人生
    2020-12-18 20:49

    You could create a template that returns a std::vector < std::vector > and receives the vector you want split, and the number of divisions. using for and iterator is very easy.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    template
    std::vector< std::vector > split(std::vector vec, uint64_t n) {
      std::vector< std::vector > vec_of_vecs(n);
    
      uint64_t quotient = vec.size() / n;
      uint64_t reminder = vec.size() % n;
      uint64_t first = 0;
      uint64_t last;
      for (uint64_t i = 0; i < n; ++i) {
        if (i < reminder) {
          last = first + quotient + 1;
          vec_of_vecs[i] = std::vector(vec.begin() + first, vec.begin() + last);
          first = last;
      }
        else if (i != n - 1) {
        last = first +  quotient;
        vec_of_vecs[i] = std::vector(vec.begin() + first, vec.begin() + last);
        first = last;
      }
        else
        vec_of_vecs[i] = std::vector(vec.begin() + first, vec.end());
    }
    
    return vec_of_vecs;
    }
    
    #define ONE_DIMENSION 11
    #define SPLITS 3
    
    int main(void)
    {
      std::vector vector(ONE_DIMENSION);
      std::iota(std::begin(vector), std::end(vector), 1);
    
      std::vector> vecs(SPLITS);
      vecs = split(vector, SPLITS);
    
      for (uint64_t m = 0; m < vecs.size(); ++m) {
        for (auto i : vecs[m])
          std::cout << std::setw(3) << i << " ";
        std::cout << std::endl;
      }
    
    
      return 0;
    }
    

提交回复
热议问题