Open In App

How to Split List into Multiple Vectors Based on a Condition in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a list is a sequence container that stores data in non-contiguous memory locations while vectors are dynamic arrays that store data in contiguous memory locations. In this article, we will learn how to split a list into multiple vectors based on certain criteria in C++.

Example:

Input:
myList= {1,2,3,4,5,6}

Output:
// Split the list into two vectors based on odd and even elements
vec1 = {2,4,6}
vec2 = {1,3,5}

Split List into Vectors Based on a Condition

To split a std::list into multiple std::vectors based on certain condition, we can use the std::stable_partition() method provided by the STL. This function partitions the elements of a container based on a given criteria while preserving the order of the elements as well.

Syntax of std::stable_partition()

Following is the syntax to use the stable_partition function.

stable_partition(start, end, func);

Here,

  • start and end are iterators that denotes the range of elements in a container.
  • func is a function that defines the certain criteria on which the container will be splitted.

C++ Program to Split List into Vectors Based on a Condition

The following program illustrates how we can split a list into multiple vectors based on even and odd elements.

C++
// C++ Program to illustrate how to split a list into
// multiple vectors based on certain criteria in C++.
#include <algorithm>
#include <iostream>
#include <list>
#include <vector>
using namespace std;

// Function that checks if the element of the list is odd or
// even
bool isEven(int num) { return num % 2 == 0; }
int main()
{
    // Initialize a list
    list<int> li = { 1, 2, 3, 4, 5, 6 };

    // Split the list into even and odd elements using
    // stable_partition
    auto split_point
        = stable_partition(li.begin(), li.end(), isEven);

    // Create separate vectors for even and odd elements
    vector<int> even(li.begin(), split_point);
    vector<int> odd(split_point, li.end());

    // Print the elements of the list
    cout << "List Elements: ";
    for (auto ele : li) {
        cout << ele << " ";
    }
    cout << endl;

    // Print the elements from both the vectors
    cout << "Even Numbers from list: ";
    for (auto ele : even) {
        cout << ele << " ";
    }
    cout << endl;

    cout << "Odd Numbers from list: ";
    for (auto ele : odd) {
        cout << ele << " ";
    }
    return 0;
}

Output
List Elements: 2 4 6 1 3 5 
Even Numbers from list: 2 4 6 
Odd Numbers from list: 1 3 5 

Time Complexity: O(N), where N is the number of elements in the list.
Auxiliary Space: O(N)





Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads