C++ STL常用算法-64-排序算法_merge合并/reverse反转

这篇继续学习C++中的排序算法,还剩merge合并算法和reverse反转算法。合并就是把两个相同类型的容器合并到第三个容器中,这个合并是有条件的。反转就是原来是队列头部,反转后变成队列尾部。反转感觉在面试考察比较多,不管是JAVA还是C++的面试。

 

1.merge合并

作用:将两个容器合并到第三个容器

函数原型:merge(iteator v1.begin,iteator v1.end, iteator v2.begin, iteator v2.end, iteator v3.begin);

注意:

1.两个容器都需要有序,而且顺序一致,不能一个升序一个降序

2.第三个容器初始化设置大小等于前面两个容器大小之和

练习代码

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;


void Print01(int val)
{
    cout << val << " ";
};

void test01()
{
    vector<int> v1;
    vector<int> v2;

    for(int i = 0; i < 10; i++)
    {
        v1.push_back(i);  // 0 到9 序列
        v1.push_back(i+1); //1到10 序列
    }

    // merge 容器合并
    vector<int> v3;
    v3.resize(v1.size() + v2.size());
    merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
    for_each(v3.begin(), v3.end(), Print01);
    cout << endl;

}

int main()
{
    test01();
    system("pause");
    return 0;
}

测试结果:

 

2.reverse反转

将容器内元素进行反转

函数原型:reverse(iteator begin, iteator end);

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;


void Print01(int val)
{
    cout << val << " ";
};

void test01()
{
    vector<int> v1;
    v1.push_back(10);
    v1.push_back(50);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(20);

    cout << "before reverse" << endl;
    for_each(v1.begin(), v1.end(), Print01);
    cout << endl;

    cout << "after reverse"<< endl ; 
    reverse(v1.begin(), v1.end());
    for_each(v1.begin(), v1.end(), Print01);
    cout << endl;

}

int main()
{
    test01();
    system("pause");
    return 0;
}

运行结果

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值