当前位置:   article > 正文

STL——常用排序算法

STL——常用排序算法

 1.sort()

 

  1. void MyPrint(int val)
  2. {
  3. cout << val << " ";
  4. }
  5. void test01()
  6. {
  7. vector<int> v1;
  8. v1.push_back(10);
  9. v1.push_back(20);
  10. v1.push_back(40);
  11. v1.push_back(30);
  12. v1.push_back(20);
  13. v1.push_back(40);
  14. v1.push_back(50);
  15. sort(v1.begin(), v1.end(), greater<int>());//用内建函数模板实现降序
  16. for_each(v1.begin(), v1.end(), MyPrint);
  17. cout << endl;
  18. }

2.random_shuffle()//随机打乱顺序

  1. void MyPrint(int val)
  2. {
  3. cout << val << " ";
  4. }
  5. void test01()
  6. {
  7. vector<int> v1;
  8. srand((unsigned int)time(NULL));//随机数种子
  9. for (int i = 0; i < 10; i++)
  10. {
  11. v1.push_back(i);
  12. }
  13. for_each(v1.begin(), v1.end(), MyPrint);
  14. cout << endl;
  15. cout << "随机打乱顺序后" << endl;
  16. random_shuffle(v1.begin(), v1.end());//随机打乱顺序
  17. for_each(v1.begin(), v1.end(), MyPrint);
  18. cout << endl;
  19. }

 3.merge()//归并

 

  1. void MyPrint(int val)
  2. {
  3. cout << val << " ";
  4. }
  5. void test01()
  6. {
  7. vector<int> v1;
  8. vector<int> v2;
  9. for (int i = 0; i < 10; i++)
  10. {
  11. v1.push_back(i);
  12. v2.push_back(i + 1);
  13. }
  14. vector<int> v3;
  15. v3.resize(v1.size() + v2.size());//归并前必须先开辟空间
  16. merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());//必须是有序且升序
  17. for_each(v3.begin(), v3.end(), MyPrint);
  18. cout << endl;
  19. }

4.reverse()//反转

  1. void MyPrint(int val)
  2. {
  3. cout << val << " ";
  4. }
  5. void test01()
  6. {
  7. vector<int> v1;
  8. for (int i = 0; i < 10; i++)
  9. {
  10. v1.push_back(i);
  11. }
  12. cout << "反转前:" << endl;
  13. for_each(v1.begin(), v1.end(), MyPrint);
  14. cout << endl;
  15. reverse(v1.begin(), v1.end());//实现反转
  16. cout << "反转后:" << endl;
  17. for_each(v1.begin(), v1.end(), MyPrint);
  18. cout << endl;
  19. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/913035
推荐阅读
相关标签
  

闽ICP备14008679号