导入
简介
本章介绍了C++17支持的各种计算算法。
标准模板库提供了大量用于操作容器及其元素的算法。由于这些算法是函数模板,因此它们与容器中元素的类型无关。连接容器和算法的是迭代器。只要你的容器支持STL容器的接口,就可以在该容器上使用这些标准算法。
1// algorithm.cpp 2#include <iostream> 3#include <algorithm> 4#include <deque> 5#include <iostream> 6#include <list> 7#include <string> 8#include <vector> 9 10template <typename Cont, typename T> 11void doTheSame(Cont cont, T t){ 12 for (const auto c: cont) std::cout << c << " "; 13 std::cout << std::endl; 14 std::cout << cont.size() << std::endl; 15 std::reverse(cont.begin(), cont.end()); 16 for (const auto c: cont) std::cout << c << " "; 17 std::cout << std::endl; 18 std::reverse(cont.begin(), cont.end()); 19 for (const auto c: cont) std::cout << c << " "; 20 std::cout << std::endl; 21 auto It= std::find(cont.begin(), cont.end(), t); 22 std::reverse(It, cont.end()); 23 for (const auto c: cont) std::cout << c << " "; 24} 25 26int main(){ 27 std::vector<int> myVec{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 28 std::deque<std::string> myDeq({"A", "B", "C", "D", "E", "F", "G", "H", "I"}); 29 std::list<char> myList({'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}); 30 31 doTheSame(myVec, 5); 32 std::cout << "\n\n"; 33 // 1 2 3 4 5 6 7 8 9 10 34 // 10 35 // 10 9 8 7 6 5 4 3 2 1 36 // 1 2 3 4 5 6 7 8 9 10 37 // 1 2 3 4 10 9 8 7 6 5 38 39 doTheSame(myDeq, "D"); 40 std::cout << "\n\n"; 41 // A B C D E F G H I 42 // 9 43 // I H G F E D C B A 44 // A B C D E F G H I 45 // A B C I H G F E D 46 47 doTheSame(myList, 'd'); 48 std::cout << "\n\n"; 49 // a b c d e f g h 50 // 8 51 // h g f e d c b a 52 // a b c d e f g h 53 // a b c h g f e d 54 55 return 0; 56}