[英]How to extract the remaining elements from std::sample
In the sample code here it shows cases how to use std::sample as shown below在此处的示例代码中,它显示了如何使用 std::sample 的情况,如下所示
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, eg hed
.我的问题不仅是我想要
gfcba
我还想提取未采样的剩余元素,例如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.我知道我可以写一个for循环比较
in
和out
提取剩余的元素,但我想知道是否有这样做更有效的方式。
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:如果您不关心输出字符串中字符的顺序,那么您可以使用
std::shuffle
随机化输入字符串,然后将结果的前 5 个字符复制到一个输出字符串,将最后 3 个字符复制到其他:
#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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.