OneBite.Dev - Coding blog in a bite size

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.

  1. Including Necessary Libraries: The code first includes necessary libraries. iostream for standard input/output streams, and vector which allows dynamic array operations.

  2. 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).

  3. Iterating Over Elements: A for loop is started which iterates over the vector nums. The loop’s increment is K, which means it’s traversing the input array in blocks of size K.

  4. 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.

  5. 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.

  6. Adding to Result: This temporary vector temp is added to the result vector which is a vector of vectors.

  7. 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.

c-plus-plus