- P251. 常用排序算法——sort
- P252. ...——random_shuffle
- P253. ...——merge
- P254. ...——reverse
- P251. sort
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <functional> //用greater 5 using namespace std; 6 7 //排序算法 sort 8 void test01() 9 { 10 vector<int>v; 11 v.push_back(20); 12 v.push_back(10); 13 v.push_back(50); 14 v.push_back(40); 15 v.push_back(30); 16 17 //利用sort升序 18 sort(v.begin(), v.end()); 19 //打印输出 20 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 21 { 22 cout << *it << " "; 23 } 24 cout << endl; 25 26 //降序 27 sort(v.begin(), v.end(), greater<int>()); 28 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 29 { 30 cout << *it << " "; 31 } 32 cout << endl; 33 } 34 35 int main() 36 { 37 test01(); 38 return 0; 39 }
运行结果:
- P252. random_shuffle
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <ctime> //为了添加随机数种子的 5 using namespace std; 6 8 void test01() 9 { 10 srand((unsigned int)time(NULL)); //添加随机数种子,不然每次用random_shuffle打乱的顺序都是一样的 11 12 vector<int>v; 13 for (int i = 0; i < 10; i++) 14 { 15 v.push_back(i); 16 } 17 18 //利用洗牌算法 打乱顺序 19 random_shuffle(v.begin(), v.end()); 20 21 //打印输出 22 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 23 { 24 cout << *it << " "; 25 } 26 cout << endl; 27 28 } 29 30 int main() 31 { 32 test01(); 33 return 0; 34 }
运行结果:
使用时记得添加随机数种子
- P253. merge
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 using namespace std; 5 6 //merge 7 void test01() 8 { 9 vector<int>v1; 10 vector<int>v2; 11 12 //原容器需要是有序序列 13 for (int i = 0; i < 10; i++) 14 { 15 v1.push_back(i); 16 v2.push_back(i + 1); 17 } 18 19 //准备一个目标容器 20 vector<int>vTarget; 21 //提前给目标容器分配空间(否则运行时会报错) 22 vTarget.resize(v1.size() + v2.size()); 23 24 merge(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin()); 25 26 for (vector<int>::iterator it = vTarget.begin(); it != vTarget.end(); it++) 27 { 28 cout << *it << " "; 29 } 30 cout << endl; 31 } 32 33 int main() 34 { 35 test01(); 36 return 0; 37 }
运行结果:
- P254. reverse
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 using namespace std; 5 6 //reverse 7 void test01() 8 { 9 vector<int>v; 10 v.push_back(1); 11 v.push_back(3); 12 v.push_back(5); 13 v.push_back(2); 14 v.push_back(4); 15 16 cout << "反转前:" << endl; 17 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 18 { 19 cout << *it << " "; 20 } 21 cout << endl; 22 23 reverse(v.begin(), v.end()); 24 cout << "反转后:" << endl; 25 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 26 { 27 cout << *it << " "; 28 } 29 cout << endl; 30 } 31 32 int main() 33 { 34 test01(); 35 return 0; 36 }
运行结果:
(〃>_<;〃)(〃>_<;〃)(〃>_<;〃)
标签:sort,begin,shuffle,reverse,++,back,push,end,include From: https://www.cnblogs.com/wjjgame/p/17341055.html