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