c++ STL(2)
阿新 • • 發佈:2018-05-15
transform ace partition out bsp each AC fill 2個
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 }
運行結果:
c++ STL(2)