STL打乱与翻转算法

#include <iostream>

#include <vector>

#include <algorithm>

#include <time.h>

 

using namespace std;

 

void printV(int i)

{

    cout << i << ends;

}

//random_shuffle对指定范围内的元素随机调整次序。

void test_random_shuffle()

{

    srand(time(0)); //设置随机种子

    vector<int> v1;

    v1.push_back(1);

    v1.push_back(3);

    v1.push_back(5);

    v1.push_back(7);

    cout << "v1打乱前:" << ends;

    for_each(v1.begin(), v1.end(), printV);

    random_shuffle(v1.begin(), v1.end());

    cout << "\n" << "v1打乱后:" << ends;

    for_each(v1.begin(), v1.end(), printV);

    string str = "abcdefg";

    cout << "\n" << "str打乱前:" << str << endl;

    random_shuffle(str.begin(), str.end());

    cout << "str打乱后: " << str << endl;

}

 

// reverse翻转/将指定范围内元素重新反序排序

void test_reverse()

{

    vector<int> vecInt;

    vecInt.push_back(1);

    vecInt.push_back(3);

    vecInt.push_back(5);

    vecInt.push_back(7);

    vecInt.push_back(9);

    cout << "反转前:" << ends;

    for_each(vecInt.begin(), vecInt.end(), printV);

    reverse(vecInt.begin(), vecInt.end());

    cout << "\n" << "反转后:" << ends;

    for_each(vecInt.begin(), vecInt.end(), printV);

}

void main()

{

    test_random_shuffle();

    test_reverse();

cout << endl;

}

结果图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值