Learn++ Lesson 65: The std::sample Function in C++ Programming

Introduction

In C++ programming, std::sample is a function that enables the random sampling of elements from a given range. It's particularly useful for selecting a random subset from a collection without modifying the original set.

Implementing std::sample

In example65.cpp, std::sample is employed to demonstrate its functionality:

Using std::sample

  • A vector v is initialized with elements 1 to 5.
  • Another vector out is created to hold the sampled elements, with a size of 2.
  • std::sample is used to randomly select two elements from v and store them in out.
  • The contents of out are printed, showcasing the random selection.

Advantages

  • Offers a straightforward way to perform random sampling from collections.
  • Ensures unbiased and random selection without altering the original set.

Applications

  • Ideal for scenarios like creating random subsets for testing or sampling in statistical analysis.
  • Useful in algorithms that require random element selection for simulations or data processing.

The std::sample function in C++ is a key tool for random sampling from collections, enhancing the flexibility and capabilities of algorithms requiring random selection.

A small example looks like this

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

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    std::vector<int> out(2);

    // Use a fixed seed instead of std::random_device
    unsigned int fixed_seed = 12345;
    std::mt19937 generator(fixed_seed);

    std::sample(v.begin(), v.end(), out.begin(), 2, generator);

    for (int x : out) {
        std::cout << x << " ";
    }
    return 0;
}

What you practice in the app

  • Understanding The std::sample Function
  • Reading the accompanying C++ example
  • Solving the lesson challenge