简体   繁体   中英

DIvide the array into K subarrays

Basically, I have an array like {5,4,3,2,1} so I need this array split into k subarrays lets take k=15. So now I need 15 subarrays. How do I do that?

Thanks.

Seems like you're looking for Pagination. Here is an example how to use the pattern:

template<typename Iterator>
struct IteratorRange {
    Iterator m_begin, m_end;
/*some impl*/
}

template <typename Iterator>
class Paginator{
private:
    vector<IteratorRange<Iterator>> m_vec;
public:
    Paginator(Iterator begin, Iterator end, size_t page_size);
/*some impl*/
};

template <typename T>
auto Paginate(T& c, size_t page_size) {
    return Paginator(c.begin(), c.end(), page_size);
}

std::vector<int> vec(15); //suppose we have a vector that needs to be divided into parts

std::iota(begin(vec), end(vec), 1);

Paginator<std::vector<int>::iterator> paginate_v(vec.begin(), vec.end(), 6);
//or: auto paginate_v = Paginate(vec, 6);
std::ostringstream os; 
for (const auto& page : paginate_v) {
  for (int x : page) {
    os << x << ' ';
  }
  os << '\n';
}

Output stream will contain: "1 2 3 4 5 6 \n7 8 9 10 11 12 \n13 14 15 \n"

I do not provide the complete impl here.

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