• 学习笔记-C++ STL iterator与对指针的理解-20170618


    vector的itrerator支持random access

     1 #include<iostream>
     2 #include<vector>
     3 using namespace std;
     4 int main()
     5 {
     6     vector<int>intVector;
     7     intVector.push_back(10);
     8     intVector.push_back(20);
     9     intVector.push_back(30);
    10     intVector.push_back(40);
    11     intVector.push_back(50);
    12     intVector.push_back(60);
    13 
    14     vector<int>::iterator p1 = intVector.begin();
    15     for (; p1 != intVector.end(); p1++)
    16     {
    17         cout << *p1 <<" " <<&p1<<endl;
    18     }
    19     //cout <<endl<< "the last" << *p1 << endl; //  vector iterator is not dereferencable 
    20     cout <<endl<< &p1 <<endl;
    21     cout  << *(--p1) << "  "<<&p1<<endl;//60
    22 
    23     cout << *(p1 - 3) <<" "<<&p1<< endl;
    24     cout << p1[-3] << " "<<&p1<<endl;
    25     cout << *p1 << "  " << &p1<< endl;
    26     *p1 = 1234;
    27     cout << *p1 << " " << &p1 << endl;
    28     for (; p1 != intVector.end(); p1++)
    29     {
    30         cout << *p1 << " " << &p1 << endl;
    31     }
    32     cout << endl << endl;
    33     for (p1=intVector.begin(); p1 != intVector.end(); p1++)
    34     {
    35         cout << *p1 << " " << &p1 << endl;
    36     }
    37     cin.get();
    38     return 0;
    39 }

    输出:

    10 00FEFCF4
    20 00FEFCF4
    30 00FEFCF4
    40 00FEFCF4
    50 00FEFCF4
    60 00FEFCF4

    00FEFCF4
    60  00FEFCF4
    30 00FEFCF4
    30 00FEFCF4
    60  00FEFCF4
    1234 00FEFCF4
    1234 00FEFCF4


    10 00FEFCF4
    20 00FEFCF4
    30 00FEFCF4
    40 00FEFCF4
    50 00FEFCF4
    1234 00FEFCF4

    PS:①当iterator指向容器中最后一个元素后面一个位置时(空),无法解引用

             ②iterator相当于指针,对iterator进行++或--时,iterator指向的位置前移或后移,但是iterator本身的地址是不变的,和指针一样

  • 相关阅读:
    谈一谈对象池SafeObjectPool能干什么
    .net core 程序退出事件
    .NETCore 快速开发做一个简易商城
    Git创建子分支,合并分支并提交
    Vue项目中关闭eslint的方法
    Missing space before function parentheses
    单引号变双引号 格式化去掉分号
    Docker Swarm搭建多服务器下Docker集群
    Asp.Net Core中服务的生命周期选项区别和用法
    KnockoutJS-模板绑定
  • 原文地址:https://www.cnblogs.com/lanmaos/p/7045391.html
Copyright © 2020-2023  润新知