random_shuffle() 随机化

转自:https://blog.csdn.net/vivi_wang_11/article/details/7441803

其他文章:https://blog.csdn.net/lionet_whitney/article/details/51086172

STL中的函数random_shuffle()用来对一个元素序列进行重新排序(随机的),函数原型如下:

template<class RandomAccessIterator>
   void random_shuffle(
      RandomAccessIterator _First, //指向序列首元素的迭代器
      RandomAccessIterator _Last  //指向序列最后一个元素的下一个位置的迭代器
   );

(自己添加的例子) (其余为转载):

#include <bits/stdc++.h>
using namespace std;

int main()
{
    char b[]="abcde";
    char a[10];
    cout<<"char:"<<endl;
    for(int i=0;i<10;i++)
    {
        strcpy(a,b);
        random_shuffle(a,a+5);
        cout<<a<<endl;
    }

    int c[]={1,2,3,4,5};
    int d[10];
    cout<<endl<<"int:"<<endl;
    for(int i=0;i<10;i++)
    {
        memcpy(d,c,sizeof(c));
        random_shuffle(d,d+5);
        for(int j=0;j<5;j++) cout<<d[j]<<" ";
        cout<<endl;
    }
}

例子:

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
	 vector<string> str;
	 str.push_back("hello");
	 str.push_back("world");
	 str.push_back("welcome");
	 str.push_back("to");
	 str.push_back("Beijing");
 
	 std::random_shuffle(str.begin(),str.end());//迭代器
 
	 for(int j = 0; j < str.size(); j++)
	 {
		 cout<<str[j].c_str()<<" ";
	 }
	 cout<<endl;
 
    system("pause");
	return 0;
}

random_shuffle还可以用于数组:

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
	char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'};
 
	 std::random_shuffle(arr,arr+6);//迭代器
 
	 for(int j = 0; j < 6; j++)
	 {
		 cout<<arr[j]<<" ";
	 }
	 cout<<endl;
 
    system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hxc2101/article/details/82633129
今日推荐