当前位置:   article > 正文

C++ STL vector 定义 操作(各种正反向遍历是重点)_c++ 向量里的元素反向循环

c++ 向量里的元素反向循环

(一)了解vector
vector是一个容器,可容纳不同的类型;
常见操作是初始化、push_back/pop_back/insert/erase/clear data to vector、各种正反向遍历、排序与二维定义及遍历。

(二)Test Demo

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5. int main()
  6. {
  7. cout << "*********************Demo1:initial a vector************************" << endl;
  8. vector<int> a;
  9. vector<char> b;
  10. vector<int> c = a, d(a);
  11. vector<int> e(3, 1), f(3);
  12. vector<int> g = {1, 2, 3, 4}, h{ 1, 2, 3, 4 };
  13. cout << "*********************Demo2:vector options************************" << endl;
  14. cout << "(1)push_back/pop_back/insert/erase/clear data to vector" << endl;
  15. for (size_t i = 0; i < 5; i++)
  16. {
  17. a.push_back(i);
  18. }
  19. cout << "(2)遍历 vector" << endl;
  20. for (auto it:a) {
  21. cout << it;//auto默认为int 故it不用解引用
  22. }
  23. cout << endl;
  24. for (vector<int>::iterator it = a.begin(); it != a.end(); ++it) {
  25. cout << *it;
  26. }
  27. cout << endl;
  28. cout << "使用反向迭代器" << endl;
  29. for (auto rit = a.rbegin(); rit != a.rend(); ++rit) {//注意注意迭代器是反向+
  30. cout << *rit;
  31. }
  32. //还可以用a.at(index); or a[index];
  33. int aaa = a.at(a.size()-1);
  34. cout << "尾部元素" << aaa << endl;
  35. cout << "*********************Demo3:vector sort************************" << endl;
  36. vector<int> num{1, 3, 1, 8, 4, 2};
  37. cout << "sort:";
  38. sort(num.begin(), num.end());//sort 与reverse 参数必须传入vector的地址,函数定义在algorithm中
  39. for (auto it : num)
  40. cout << it;
  41. cout << endl;
  42. cout << "reverse:";
  43. reverse(num.begin(), num.end());
  44. for (auto it : num)
  45. cout << it;
  46. cout << endl;
  47. cout << "*********************Demo4:vector 二维定义************************" << endl;
  48. vector<vector<int>> twoarray(5, vector<int>(6));//5*6
  49. for (vector<vector<int>>::iterator it = twoarray.begin(); it != twoarray.end(); ++it) {
  50. /*for (auto it1 :*it) {
  51. it1 = int(rand()&0xff) ;
  52. }*/
  53. for (vector<int>::iterator it1 = (*it).begin(); it1 != (*it).end(); ++it1) {
  54. *it1 = int(rand()&0xFF);
  55. }
  56. }
  57. cout << endl;
  58. for (auto it:twoarray) {
  59. for (auto it1 : it) {
  60. cout << it1 << " ";
  61. }
  62. cout << endl;
  63. }
  64. cout << endl;
  65. return 0;
  66. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/390832
推荐阅读
相关标签
  

闽ICP备14008679号