【问题标题】:How to access class variable inside a vector iterator?如何访问向量迭代器中的类变量?
【发布时间】:2019-05-07 10:48:37
【问题描述】:

我想访问类实例的公共变量,其中实例保存在类类型的向量中。我必须使用迭代器遍历向量的所有元素,但这让我很困惑如何在存在迭代器的情况下获取变量。我使用的是 C++98。

source.cpp:

#include <iostream>
#include <vector>
#include "Rectangle.h" 

using namespace std;

int main() {    
    int len = 2, hen = 5;   
    int len2 = 4, hen2 = 10;

    Rectangle rect1(len, hen);  
    Rectangle rect2(len2, hen2);        
    vector<Rectangle> Rects;
    Rects.push_back(rect1);
    Rects.push_back(rect2);

    for (std::vector<Rectangle>::iterator it = Rects.begin(); it != Rects.end(); ++it) {        
       //how to access length and height here?  
    }

    system("pause");    
    return 0; 
}

矩形.h:

#pragma once
class Rectangle
{
private:        

public:
    int length;
    int height;

    Rectangle(int& length, int& height);
    ~Rectangle();
};

矩形.cpp:

#include "Rectangle.h"

Rectangle::Rectangle(int& length, int& height) 
    : length(length), height(height)
{ }

Rectangle::~Rectangle() {}

【问题讨论】:

  • 迭代器的行为很像指针,所以it-&gt;length(*it).length 都会做你想做的事(在所有情况下都喜欢前者)。
  • 只是为了澄清:迭代器内部没有值。更好的理解方式是迭代器是指向容器的精美指针。元素在容器中,迭代器只是指向它们(假设它是一个有效的迭代器)
  • 有什么特殊原因,您使用的是 20 年前的标准吗?
  • @bitmask 你的意思是c++98?我正在研究微控制器。并非所有编译器都支持 c++11 或更高版本。

标签: c++ c++98


【解决方案1】:

首先将矩形添加到向量,取消引用迭代器并访问元素。

int main() {    
    int len = 2, hen = 5;   
    int len2 = 4, hen2 = 10;

    Rectangle rect1(len, hen);  
    Rectangle rect2(len2, hen2);        
    vector<Rectangle> Rects;
    Rects.push_back(rect1);
    Rects.push_back(rect2);

    for (std::vector<Rectangle>::iterator it = Rects.begin(); it != Rects.end(); ++it) {        
       std::cout << "length " <<(*it).length<<std::endl;
       std::cout << "height " <<(*it).height<<std::endl;
    }

    system("pause");    
    return 0; 
}

【讨论】:

  • 为了完整性,另一种解引用类的指针(迭代器)并访问它的成员的方法是使用箭头运算符-&gt;,它结合了解引用*和成员访问. 运营商。因此,it-&gt;lengthit-&gt;height 也可以使用。
猜你喜欢
  • 1970-01-01
  • 2010-09-30
  • 2016-08-25
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 2012-03-19
  • 2017-08-29
  • 1970-01-01
相关资源
最近更新 更多