简体   繁体   English

如何在向量迭代器内访问类变量?

[英]How to access class variable inside a vector iterator?

I'd like to access a public variable of a class instance, where the instances are kept in a vector of the class type. 我想访问一个类实例的公共变量,其中实例保存在类类型的向量中。 I have to run through all elements of vector using an iterator, but it confuses me as to how I get the variables with the iterator present. 我必须使用迭代器来遍历vector的所有元素,但这使我困惑如何在存在迭代器的情况下获取变量。 I'm using C++98. 我正在使用C ++ 98。

source.cpp: 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; 
}

Rectangle.h: Rectangle.h:

#pragma once
class Rectangle
{
private:        

public:
    int length;
    int height;

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

Rectangle.cpp: Rectangle.cpp:

#include "Rectangle.h"

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

Rectangle::~Rectangle() {}

Add the rectangle to vector first, dereference iterator and access the elements. 首先将矩形添加到vector,解引用迭代器并访问元素。

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; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM