Split a vector into sub-vectors of size n in C++
Write an algorithm to split a vector into sub-vectors of size n in C++.
Splitting a vector into sub-vectors of a specific size is very easy in C++. We start by determining the total number of sub-vectors of size n formed from the input vector. Then we iterate the given vector, and in each iteration of the loop, we process the next set of n elements and copy it to a new vector using the std::copy algorithm. We need to take special care about the boundary conditions.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
#include <iostream> #include <vector> // Utility function to print a vector template<typename T> void print(std::vector<T> const &v) { for (auto &i: v) { std::cout << i << ' '; } std::cout << std::endl; } // Split a vector into sub-vectors of size `n` in C++ int main() { // input vector of integers std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // split vector into sub-vectors each of size `n` int n = 4; // determine the total number of sub-vectors of size `n` int size = (v.size() - 1) / n + 1; // create an array of vectors to store the sub-vectors std::vector<int> vec[size]; // each iteration of this loop process the next set of `n` elements // and store it in a vector at k'th index in `vec` for (int k = 0; k < size; ++k) { // get range for the next set of `n` elements auto start_itr = std::next(v.cbegin(), k*n); auto end_itr = std::next(v.cbegin(), k*n + n); // allocate memory for the sub-vector vec[k].resize(n); // code to handle the last sub-vector as it might // contain fewer elements if (k*n + n > v.size()) { end_itr = v.cend(); vec[k].resize(v.size() - k*n); } // copy elements from the input range to the sub-vector std::copy(start_itr, end_itr, vec[k].begin()); } // print the sub-vectors for (int i = 0; i < size; i++) { print(vec[i]); } return 0; } |
Output:
1 2 3 4
5 6 7 8
9 10
That’s all about splitting a vector into sub-vectors of size n in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)