C++ 常用排序算法
生活随笔
收集整理的這篇文章主要介紹了
C++ 常用排序算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include <algorithm>
#include <vector>
#include <functional>
#include <ctime>
/*
merge算法 容器元素合并,并存儲到另一容器中 這兩個容器 必須也是有序的
@param beg1 容器1開始迭代器
@param end1 容器1結束迭代器
@param beg2 容器2開始迭代器
@param end2 容器2結束迭代器
@param dest 目標容器開始迭代器
*/
void test01()
{vector<int>v1;vector<int>v2;for (int i = 0; i < 10;i++){v1.push_back(i);v2.push_back(i + 1);}vector<int>vTarget;vTarget.resize(v1.size() + v2.size());merge(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());for_each(vTarget.begin(), vTarget.end(), [](int v){ cout << v << " "; });
}/*
sort算法 容器元素排序
注意:兩個容器必須是有序的
@param beg 容器1開始迭代器
@param end 容器1結束迭代器
@param _callback 回調函數或者謂詞(返回bool類型的函數對象)
*/
void test02()
{vector<int>v1;v1.push_back(10);v1.push_back(40);v1.push_back(20);v1.push_back(90);v1.push_back(50);sort(v1.begin(), v1.end());for_each(v1.begin(), v1.end(), [](int val){cout << val << " "; });cout << endl;sort(v1.begin(), v1.end(), greater<int>());for_each(v1.begin(), v1.end(), [](int val){cout << val << " "; });cout << endl;
}//random_shuffle(iterator beg, iterator end) 洗牌
void test03()
{vector<int>v;for (int i = 0; i < 10;i++){v.push_back(i);}random_shuffle(v.begin(), v.end());for_each(v.begin(), v.end(), [](int val){cout << val << " "; });
}//reverse(iterator beg, iterator end)
void test04()
{vector<int>v;for (int i = 0; i < 10; i++){v.push_back(i);}reverse(v.begin(), v.end());for_each(v.begin(), v.end(), [](int val){cout << val << " "; });
}int main(){srand((unsigned int)time(NULL));//test01();//test02();//test03();test04();system("pause");return EXIT_SUCCESS;
}
總結
以上是生活随笔為你收集整理的C++ 常用排序算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ 常用查找算法
- 下一篇: C++ 常用拷贝和替换算法