c++ STL常用算法使用方法
#include <string> #include <vector> #include <functional> #include <iostream> using namespace std; void print(vector< int >& list, const string &des) { cout<< "after " <<des.c_str()<< ", the list is: " <<endl; for (vector< int >::iterator iter = list.begin(); iter != list.end(); ++iter) { cout<<(*iter)<< " " ; } cout<<endl; } void printstr(vector<string>& list, const string &des) { cout<< "after " <<des.c_str()<< ", the list is: " <<endl; for (vector<string>::iterator iter = list.begin(); iter != list.end(); ++iter) { cout<<(*iter)<< " " ; } cout<<endl; } template < class T> struct comp: public std::binary_function<T,T, bool > { bool operator()( const T &t1, const T &t2) const { return t1 > t2; } }; struct conv : public std::unary_function<string, string> { string& operator()(string &str) { std::transform(str.begin(), str.end(), str.begin(), :: tolower ); return str; } }; int main() { vector< int > list; list.push_back(2324); list.push_back(45); list.push_back(576); list.push_back(768); list.push_back(21); list.push_back(4); list.push_back(1); list.push_back(54758); list.push_back(123); list.push_back(464); list.push_back(88); print(list, "push back" ); std::sort(list.begin(), list.end()); print(list, "normal sort" ); vector< int >::iterator iter = lower_bound(list.begin(), list.end(), 5); cout<< "lower find element is 5, value " <<(*iter)<<endl; iter = upper_bound(list.begin(), list.end(), 5); cout<< "upper find element is 5, value " <<(*iter)<<endl; bool ret = std::binary_search(list.begin(), list.end(), 464); if (ret) { cout<< "find 464, value ok." <<endl; } std::sort(list.begin(), list.end(), comp< int >()); print(list, "big sort" ); iter = lower_bound(list.begin(), list.end(), 5); cout<< "lower find element is 5, value " <<(*iter)<<endl; iter = upper_bound(list.begin(), list.end(), 5); cout<< "upper find element is 5, value " <<(*iter)<<endl; ret = std::binary_search(list.begin(), list.end(), 88, comp< int >()); if (ret) { cout<< "find 88, value ok." <<endl; } list.insert(std::upper_bound(list.begin(), list.end(), 55, comp< int >()), 55); print(list, "upper bound insert" ); list.insert(std::lower_bound(list.begin(), list.end(), 77, comp< int >()), 77); print(list, "lower bound insert" ); iter = std::search(list.begin(), list.end(), list.begin() + 4, list.begin() + 6); if (iter != list.end()) { cout<< "search seq pos is " <<(*iter)<<endl; } vector<string> strList; strList.push_back( "AAAA" ); strList.push_back( "BBBB" ); strList.push_back( "CCCC" ); printstr(strList, "str list" ); std::transform(strList.begin(), strList.end(), strList.begin(), conv()); printstr(strList, "transform" ); // sort之后才能执行unique return 0; } |
上面的使用主要起到抛砖引玉的作用,可根据实际情况借鉴使用方法使用其它算法。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步