Partition Algorithms

Partitioning Custom Data Types

Can the partition() function be used with custom data types, and if so, how?

Abstract art representing computer programming

Yes, the partition() function can be used with custom data types in C++. To do this, you need to define a predicate that operates on the members of your custom type.

The predicate determines how the objects are divided into partitions. Consider the following custom type Actor:

#include <string>

enum class Mood { Friendly, Neutral, Hostile };

class Actor {
public:
  Actor(std::string Name, Mood Mood)
    : Name{Name}, Mood{Mood} {}

  std::string Name;
  Mood Mood;
};

To partition a collection of Actor objects such that all friendly actors are separated from the others, you can define a predicate that checks the Mood of each Actor and use it with std::ranges::partition().

Here’s an example:

#include <algorithm>
#include <iostream>
#include <vector>

enum class Mood { Friendly, Neutral, Hostile };

class Actor {/*...*/}; int main() { using enum Mood; std::vector<Actor> Actors{ {"Angry Goblin", Hostile}, {"Helpful Guard", Friendly}, {"Surly Goat", Neutral}, }; auto isFriendly = [](const Actor& A) { return A.Mood == Friendly; }; std::ranges::partition(Actors, isFriendly); std::cout << "After partitioning: "; for (const Actor& A : Actors) { std::cout << A.Name << ", "; } std::cout << "\n"; }
After partitioning: Helpful Guard, Angry Goblin, Surly Goat,

In this example, the isFriendly predicate checks if an Actor is friendly. The partition() function then rearranges the Actors vector so that all friendly actors are placed at the beginning.

Using partition() with custom data types is a powerful way to organize complex collections based on specific criteria defined by your predicates. Ensure your predicate function is well-defined to avoid unexpected behavior.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved