c++ - 如何访问 vector 迭代器中的类变量?

标签 c++ c++98

我想访问类实例的公共(public)变量,其中实例保存在类类型的 vector 中。我必须使用迭代器遍历 vector 的所有元素,但是对于如何使用迭代器获取变量这让我感到困惑。我正在使用 C++98。

源代码.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() {}

最佳答案

首先将矩形添加到 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; 
}

关于c++ - 如何访问 vector 迭代器中的类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56020906/

相关文章:

c++ - map 的键可以是数组吗? (映射数组错误)

c++ - 关于使用 memcpy 将表达式值复制到指针的查询

c++ - 存储成员函数模板实例时出错

c++ - 使用 fstream 从文本文件中读取数据

c++ - 在链表程序中使用模板时在 C++ 中重载 << 运算符

c++ - 节流 C++ 线程

c++ - C++名称查找在这里做什么? (& GCC 对吗?)

c++ - 是 case statement1 + statement2 : poor coding?

c++ - 有条件地迭代某些项目

c++ - C++ 是否保证 header 初始化的静态 const 成员在编译单元和库之间共享单个实例?