C++學習筆記之泛型算法
阿新 • • 發佈:2017-07-04
vector ace sort clu 算法 clas uniq bits 有時
先貼個代碼 有時間的再補筆記
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 //模板類在接收了參數之後會將參數實例化 5 //自然可以接收 vector<string> 和 vector<int> 6 7 template<typename T> void print(T vec) //打印該實例 8 { 9 for(auto it:vec) 10 { 11 cout<<it<<" "; 12} 13 cout<<endl; 14 } 15 16 template<typename T> void solve(T &vec) //經典的去重算法 17 { 18 print(vec); 19 sort(vec.begin(),vec.end()); //排序 20 auto over=unique(vec.begin(),vec.end()); //去重 21 vec.erase(over,vec.end()); //刪除進行unique之後最後的叠代器之後的內容 22 print(vec);23 } 24 25 int main() 26 { 27 string str; 28 vector<string>vec; 29 freopen("in.txt","r",stdin); 30 while(cin>>str) 31 { 32 if(str[0]>=‘0‘&&str[0]<=‘9‘) 33 { 34 break; 35 } 36 vec.push_back(str); 37 }38 solve(vec); 39 int tmp; 40 vector<int>vec1; 41 while(cin>>tmp) 42 { 43 vec1.push_back(tmp); 44 } 45 solve(vec1); 46 return 0; 47 }
C++學習筆記之泛型算法