标准模板库(STL)

我不是女神ヾ 2022-06-08 05:38 426阅读 0赞

标准模板库(STL)

以矢量vector为例,如下程序是begin()、end()、push_back、pop_back()、erase()、insert()、sort()的用法:

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <cstdlib>
  4. #include <vector>
  5. using namespace std;
  6. vector <int>::iterator p;
  7. void show(vector <int> &a)
  8. {
  9. for(p=a.begin();p!=a.end();p++)
  10. cout<<*p<<' ';
  11. cout<<endl<<endl;
  12. }
  13. bool cmp(int a,int b)
  14. {
  15. return a>b;
  16. }
  17. int main()
  18. {
  19. vector <int> sb;
  20. p=sb.begin();
  21. int i;
  22. cout<<"Create the list , 0 to finish:"<<endl;
  23. while(cin>>i&&i)
  24. {
  25. sb.push_back(i);
  26. p++;
  27. }
  28. show(sb);
  29. cout<<"Push_back a price :"<<endl;
  30. cin>>i;
  31. sb.push_back(i);
  32. show(sb);
  33. cout<<"Delete the last one :"<<endl;
  34. sb.pop_back();
  35. show(sb);
  36. cout<<"The reserve order sort:"<<endl;
  37. sort(sb.begin(),sb.end(),cmp);
  38. show(sb);
  39. cout<<"Erase:"<<endl;//delete a interval of 3th to 5th
  40. sb.erase(sb.begin()+2,sb.begin()+5);
  41. show(sb);
  42. cout<<"Insert:"<<endl;//insert a interval of first to 3rd itself
  43. sb.insert(sb.begin(),sb.begin()+3,sb.begin()+6);
  44. show(sb);
  45. cout<<"The size of sb: "<<sb.size()<<endl;
  46. return 0;
  47. }

Center

发表评论

表情:
评论列表 (有 0 条评论,426人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C++标准模板STL学习总结

    STL提供了一组表示容器、迭代器、函数对象和算法的模板。 STL是一种泛型编程。面向对象编程关注的是编程的数据方面,而泛型编程关注的是算法。它们之间的共同点是创建可重用的代