简体   繁体   English

我如何在C ++中将给定大小的数组改组并与另一个相同大小的数组进行比较

[英]how can i shuffle an array of a given size and compare it with another array of same size in C++

suppose I have an array A={212,323,234,567,545,765} and now I want shuffle this array so that the values are arranged randomly 假设我有一个数组A = {212,323,234,567,545,765},现在我想改组这个数组,以便将值随机排列

like after shuffling it can be A={234,765,212,545,323,567} 像改组后一样可以是A = {234,765,212,545,323,567}

I am not getting any clue how to solve this problem ? 我不知道如何解决此问题的任何线索?

Check std::shuffle and std::equal . 检查std::shufflestd::equal There are some examples in documentation that will help you. 文档中有一些示例可以为您提供帮助。

For basic shuffling you'd want to use std::shuffle . 对于基本的改组,您需要使用std :: shuffle

#include <algorithm>
#include <array>
#include <random>
#include <iterator>
#include <iostream>

int main()
{
    // Create mersenne twister RNG
    std::random_device rd;
    std::mt19937 g(rd());
    // Initialize Array A
    std::array<int, 6u> A{ 212,323,234,567,545,765 };
    // Print A
    std::copy(A.begin(), A.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
    // Shuffle A
    std::shuffle(A.begin(), A.end(), g);
    // Print A
    std::copy(A.begin(), A.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM