How to extract the remaining elements from std::sample

Viewed 80

In the sample code here it shows cases how to use std::sample as shown below

std::string in = "hgfedcba", out;
std::sample(in.begin(), in.end(), std::back_inserter(out),
                5, std::mt19937{std::random_device{}()});
std::cout << "five random letters out of " << in << " : " << out << '\n';

Possible output:

five random letters out of hgfedcba: gfcba

My question is not only I want gfcba I also want to extract the remaining elements that are the not sampled, e.g. hed. I know I can write a for loop to compare in and out to extract the remaining elements, but I am wondering if there's a more efficient way to do this.

1 Answers

If you're not concerned about the order of the characters in the output strings, then you can use std::shuffle to randomise the input string and then copy the first 5 characters of the result to one output string and the last 3 to the other:

#include <iostream>
#include <random>
#include <string>
#include <algorithm>

int main ()
{
    std::string in = "hgfedcba";

    std::random_device rd;
    std::mt19937 g (rd ());
    std::shuffle (in.begin(), in.end(), g);

    std::string out5, out3;
    
    for (size_t i = 0; i < 5; ++i)
        out5.push_back (in [i]);
    for (size_t i = 5; i < 8; ++i)
        out3.push_back (in [i]);
    
    std::cout << out5 << " " << out3;
}

Sample output:

cbhfd aeg
Related