标签:iostream 元素 重复元素 class tor ever include cto info
Vector:
1 #include "stdafx.h" 2 #include<iostream> 3 #include<vector> 4 #include<algorithm> 5 using namespace std; 6 int main() 7 { 8 vector<int> v = { 10,98,76,66,67,66,90 }; 9 cout << "排序前的数组: "; 10 for (int elem : v) { 11 cout << elem << " "; //如何输出 12 } 13 cout << endl; 14 stable_sort(v.begin(), v.end()); //此排序方式为稳定排序,适用于v中有相同元素,如上面有2个66的情况, 15 //这样就不会改变两个66的相对位置。如果没有重复元素的话,用sort(v.begin(), v.end())方可 16 cout << "排序后的数组: "; 17 for (int elem : v) { 18 cout << elem << " "; //如何输出 19 } 20 cout << endl; 21 fill(v.begin()+2, v.end(), 54); //填充 22 cout << "此时的数组: "; 23 for (int elem : v) { 24 cout << elem << " "; //如何输出 25 } 26 cout << endl; 27 fill_n(v.begin(), 3, 8); //填充的另一种方式 28 cout << "此时的数组: "; 29 for (int elem : v) { 30 cout << elem << " "; //如何输出 31 } 32 cout << endl; 33 return 0; 34 }
对于上述输出方式的演变如下:现在用(3)即可
(1)
1 for_each (int elem in v) 2 { 3 cout << elem << " "; 4 }
(2)
1 for_each (v.begin(),v.end(),[](int elem) 2 { 3 cout << elem << " "; 4 }
(3)
1 for (int elem : v) 2 { 3 cout << elem << " "; 4 }
字符串大写变小写:
1 #include "stdafx.h" 2 #include<iostream> 3 #include<vector> 4 #include<string> 5 #include<algorithm> 6 using namespace std; 7 int main() 8 { 9 string s1 = "hello world."; 10 string s2; 11 transform(s1.begin(), s1.end(), s2.begin(), toupper); //同样大写变小写就是tolower 12 cout << s1 << endl; 13 }
二分查找:
1 #include "stdafx.h" 2 #include<iostream> 3 #include<vector> 4 #include<string> 5 #include<algorithm> 6 using namespace std; 7 int main() 8 { 9 vector<int> v= { 10,98,76,45,66,67,90 }; 10 if (binary_search(v.begin(), v.end(),67)) 11 cout << "Exits!" << endl; 12 else 13 cout << "Didn‘t exits!" << endl; 14 }
数列反转:
1 #include "stdafx.h" 2 #include<iostream> 3 #include<vector> 4 #include<string> 5 #include<algorithm> 6 using namespace std; 7 int main() 8 { 9 vector<int> v= { 10,98,76,45,66,67,90 }; 10 cout << "反转前的数列为: "; 11 for (int elem : v) 12 { 13 cout << elem << " "; 14 } 15 cout << endl; 16 reverse(v.begin(), v.end()); 17 cout << "反转后的数列为: "; 18 for (int elem : v) 19 { 20 cout << elem << " "; 21 } 22 cout << endl; 23 return 0; 24 }
条件分区:
1 #include "stdafx.h" 2 #include<iostream> 3 #include<vector> 4 #include<string> 5 #include<algorithm> 6 using namespace std; 7 int main() 8 { 9 vector<int> v = { 1,2,3,4,5,6,7,8,9 }; 10 stable_partition(v.begin(), v.end(), [](int elem) 11 { 12 return elem % 2 == 0; 13 }); 14 for (int elem : v) 15 { 16 cout << elem << " "; 17 } 18 cout << endl; 19 return 0; 20 }
运行结果:
标签:iostream 元素 重复元素 class tor ever include cto info
原文地址:https://www.cnblogs.com/Trojan00/p/9040446.html