Split An Array Into Smaller Arrays In C++
Code snippet for how to Split An Array Into Smaller Arrays In C++ with sample and detail explanation
Splitting an array into smaller arrays in C++ is a common problem that programmers may encounter. Understanding how to perform this task is crucial in handling large datasets and optimizing code in terms of time complexity and space usage.
Code Snippet: Splitting an Array
Here’s a simple C++ code snippet that divides an array into smaller arrays.
#include<iostream>
#include<vector>
using namespace std;
vector<vector<int>> splitArray(vector<int>& nums, int K) {
vector<vector<int>> result;
for(int i = 0; i < nums.size(); i += K) {
vector<int> temp;
for(int j = i; j < i+K && j < nums.size() ; j++) {
temp.push_back(nums[j]);
}
result.push_back(temp);
}
return result;
}
int main() {
vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int K = 3;
vector<vector<int>> result = splitArray(nums, K);
for(auto &subArray : result) {
for(int &num : subArray) {
cout << num << ' ';
}
cout << '\n';
}
return 0;
}
Code Explanation for Splitting an Array
This code logically splits an array into smaller arrays in steps. Let’s take a look at how it works.
-
Including Necessary Libraries: The code first includes necessary libraries.
iostream
for standard input/output streams, andvector
which allows dynamic array operations. -
Declaring the splitArray Function: A function named
splitArray
is declared. It takes two parameters as input: a reference to a vector of integers (nums
), and an integer (K
). -
Iterating Over Elements: A for loop is started which iterates over the vector
nums
. The loop’s increment isK
, which means it’s traversing the input array in blocks of sizeK
. -
Creating Temporary Vectors: A temporary vector
temp
is created in each iteration which will store K elements or the remaining number of elements if less than K are left. -
Filling Up Temporary Vectors: Another nested for loop starts. It takes each block of K integers (or fewer, if less than K remain), and pushes them into
temp
. -
Adding to Result: This temporary vector
temp
is added to theresult
vector which is a vector of vectors. -
Returning the Result: The
result
vector is returned by the function. This vector of vectors contains smaller arrays in which the original array has been split.
In the main
function, an array nums
is created and the splitArray
function is called with nums
and the number 3. The split up array is then printed out on the screen.
Congratulations! You have successfully split an array into smaller chunks. Using a similar approach, you can split any array into smaller pieces as per your requirement.