C++让Vector的数组随机排列

C++让Vector的数组随机排列

思路

输入:  vector<string> Array
过程: vector<string> Shuffle_ArrayOrder(vector<string> Array_tmp)
1: 新建一个map<int,int>map_tmp ,其中first从0到Array.size(),second是10000
  以内的随机数
2: 对map_tmp根据second进行排序
3: 新建一个vector<string>Array_Result,遍历map_tmp,把Array[map_tmp[i]]
  依次压入。
输出:  Array_Result

代码


vector<string> Shuffle_ArrayOrder(vector<string> Array_tmp)
{
    srand((int)time(0));
    for(int i = 0; i < Array_tmp.size(); i++)
        cout << Array_tmp[i] << "---";
    map<int, int> NumSignMap_tmp;
    for(int i = 0; i < Array_tmp.size(); i++)
    {
        int Num_random = (rand() % 10000);
        NumSignMap_tmp[i] = Num_random;
    }
    for(int i = 0; i < Array_tmp.size(); i++)
    {
        cout << i << ": " << NumSignMap_tmp[i] << endl;
    }
    vector<pair<int, int>> VectorMap_tmp;
    for (auto it = NumSignMap_tmp.begin(); it != NumSignMap_tmp.end(); it++)
        VectorMap_tmp.push_back(make_pair(it->first, it->second));

    sort(VectorMap_tmp.begin(), VectorMap_tmp.end(),
        [](const pair<int, int> &x, const pair<int, int> &y) -> int {
        return x.second < y.second;
    });

    for (auto it = VectorMap_tmp.begin(); it != VectorMap_tmp.end(); it++)
        cout << it->first << ':' << it->second << '\n';
    vector<string> Array_result = Array_tmp;
    auto it = VectorMap_tmp.begin();
    for(int i = 0; i < Array_result.size(); i++)
    {
        Array_result[i] = Array_tmp[it->first];
        it++;
    }
    cout << endl << endl;
    for(int i = 0; i < 11; i++)
    {
        cout << Array_result[i] << "----";
    }
    cout << endl;
    return Array_result;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值