C++
range-v3
programming
random_shuffle
code tutorial

How to write a range-v3 action for random_shuffle?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

The C++ `range-v3` library extends standard C++ ranges and provides a rich set of operations and views for processing sequences of data. One of its noteworthy features is the ability to define and use actions—operators that can modify the data in place. While most commonly used actions are already provided by the library, custom action creation can offer tailored functionality to suit specific needs. Here, we delve into writing a custom `range-v3` action to perform `random_shuffle`, an operation that randomizes the order of elements within a range.

Preliminary Requirements

Before diving into writing a custom action, make sure you have the following:

  1. C++ Knowledge: Basic knowledge of C++11/14/17, as `range-v3` heavily uses modern C++ features like lambdas, type traits, and range-based constructs.
  2. range-v3 Library: Install the `range-v3` library. If using CMake, you can find it on vcpkg or refer to its GitHub repository for direct cloning and building instructions.
  3. Random Shuffle Understanding: Familiarity with standard algorithms like `std::shuffle` which randomizes elements using a random number generator.

Writing a Custom Action: Random Shuffle

Step 1: Understanding Action Structure

Actions in `range-v3` can be thought of as modifying transformations. They usually provide an `operator()` that takes a range and applies transformations directly to the elements. An action typically refrains from changing the size or structure of the container.

Step 2: Template Structure of an Action

To create a custom action, follow the required steps:

  • Compile with Diagnostics: Use flags like `-Wall` and `-Wextra` to catch potential issues.
  • Unit Tests: Create test cases with libraries such as `GoogleTest` or `Catch2` for different container types and sizes.
  • Choosing the Random Engine: Use a suitable random engine for the intended use case. The default provided here is `std::default_random_engine`.
  • Iterator Category: Guidelines recommend actions that work on random-access iterators for efficiency, given that this supports quick index-based modifications.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.