zoukankan      html  css  js  c++  java
  • vector遍历

    代码:

     1 #include <iostream>
     2 #include<vector>
     3 #include<iterator>
     4 #include<algorithm>
     5 //#include<bits/stdc++.h>
     6 using namespace std;
     7 void show(vector<int>& v)
     8 {
     9     for(int i=0; i<(int)v.size(); i++)
    10     {
    11         cout<<v[i]<<" ";
    12     }
    13     cout<<endl;
    14 }
    15 int main()
    16 {
    17     //遍历vector
    18     //for循环遍历
    19     //迭代器输出
    20     //v.at(pos);特定位置的引用
    21     vector<int> v;
    22     for(int i=0; i<10; i++)
    23         v.push_back(i);
    24     for(int i=0; i<(int)v.size(); i++)
    25         cout<<v[i]<<" ";//0 1 2 3 4 5 6 7 8 9
    26     cout<<endl;
    27     vector<int>::iterator iter=v.begin();//正向迭代器
    28     for(;iter!=v.end();iter++){//*iter = 100 可以用指针 对 迭代器 进行修改操作
    29         cout<<*iter+100<<" ";//100 101 102 103 104 105 106 107 108 109
    30 
    31     }
    32     cout<<endl;
    33     vector<int>::reverse_iterator itera=v.rbegin();//反向迭代器  // 是从end-1开始的,end指向的不是最后一个元素
    34     for(;itera!=v.rend();itera++){//反向迭代器从右往左+ 从左往右 -
    35         cout<<*itera+100<<" ";//109 108 107 106 105 104 103 102 101 100
    36     }
    37     cout<<endl;
    38     show(v);//0 1 2 3 4 5 6 7 8 9
    39     reverse(v.begin(),v.end());//反转 vector
    40     show(v);//9 8 7 6 5 4 3 2 1 0
    41     reverse(v.begin()+1,v.begin()+8);//反转部分元素
    42     show(v);//9 2 3 4 5 6 7 8 1 0
    43     cout<<v.front()<<endl;//返回首元素的引用
    44     cout<<v.back()<<endl;//返回尾元素的引用
    45     cout<<v.at(2)<<endl;//返回2位置元素的引用
    46     cout<<*v.begin()<<endl;//v.begin()是迭代器需要用 *v.begin()取出来
    47     cout<<*(v.end()-1)<<endl;//返回向量尾指针,指向向量最后一个元素的下一个位置(没有元素,v.end()-1前面那个是最后一个数据)
    48     cout<<*v.rbegin()<<endl;//反向迭代器,指向最后一个元素v.end()-1
    49     cout<<*(v.rend()-1)<<endl;//反向迭代器,v.rend()指向第一个元素之前的位置 v.begin()-1; v.rend()-1是往前走的 -1-->0  v.rend()+1  是往后走的-1-->-2
    50     return 0;
    51 }

    输出:

     1 0 1 2 3 4 5 6 7 8 9
     2 100 101 102 103 104 105 106 107 108 109
     3 109 108 107 106 105 104 103 102 101 100
     4 0 1 2 3 4 5 6 7 8 9
     5 9 8 7 6 5 4 3 2 1 0
     6 9 2 3 4 5 6 7 8 1 0
     7 9
     8 0
     9 3
    10 9
    11 0
    12 0
    13 9
  • 相关阅读:
    LeetCode 769. Max Chunks To Make Sorted
    LeetCode 845. Longest Mountain in Array
    LeetCode 1059. All Paths from Source Lead to Destination
    1129. Shortest Path with Alternating Colors
    LeetCode 785. Is Graph Bipartite?
    LeetCode 802. Find Eventual Safe States
    LeetCode 1043. Partition Array for Maximum Sum
    LeetCode 841. Keys and Rooms
    LeetCode 1061. Lexicographically Smallest Equivalent String
    LeetCode 1102. Path With Maximum Minimum Value
  • 原文地址:https://www.cnblogs.com/NirobertEinteson/p/11960654.html
Copyright © 2011-2022 走看看