【问题标题】:How to change the order of an array in c++c++中如何改变数组的顺序
【发布时间】:2019-01-11 22:08:51
【问题描述】:

我正在尝试像这样更改 char 数组的顺序:

char arr_char[]="ABCDEFGHIJABCDEFGHIJ";

我在以下代码中使用了 rand() 函数:

#include <iostream>
#include <cstdlib>
#include <ctime>


using namespace std;



int main()
{
  char arr_char[]="ABCDEFGHIJABCDEFGHIJ";
  int arrSize=sizeof(arr_char)-1;

  srand(time(0));

 for(int i=0;i<20;i++)
 {
    cout<<arr_char[rand() % arrSize]<<" ";
 }
}

但是 rand 函数重复某些字符超过两次,我想更改数组的顺序,其中每个字符只重复两次而不是更多。

【问题讨论】:

  • 首先,使用 C++ &lt;random&gt; 库中的设施,而不是过时和糟糕的 C 函数。您需要的是一种打乱数组的方法,而不仅仅是输出随机元素,您可以使用std::shuffle 来完成。
  • rand() 从统计角度来看是可怕的。使用 C++11 提供的更高分辨率的随机生成器。永远不要使用该功能。
  • 为什么你希望随机函数不重复它返回的值?您不是在随机化一个数组,而是在随机选择和显示一个字符,并且这样做了 20 次。

标签: c++ arrays random char


【解决方案1】:

这可能就足够了

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

using namespace std;

int main()
{
    string arr_char = "ABCDEFGHIJABCDEFGHIJ";
    random_shuffle(arr_char.begin(), arr_char.end());
    cout << arr_char;
}

【讨论】:

  • random_shuffle 在 C++14 中已被弃用并在 C++17 中被删除。 std::shuffle 应该会更好。
猜你喜欢
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
相关资源
最近更新 更多