【发布时间】:2016-04-30 19:52:43
【问题描述】:
我在一个集合上的迭代器返回值给出了内存位置而不是值。如何访问迭代器指向的元素?
我使用了一个类似的迭代器循环,之前它工作得很好,如返回迭代器指向的值(对于双端队列和向量模板类)。
这个问题是我今天早些时候遇到困难的一个脚本的后续问题 (C++ : adding an object to a set)。
脚本现在如下所示:
头文件
#ifndef EMPLOYEE_HH
#define EMPLOYEE_HH
#include <set>
#include <string>
#include <iostream>
using namespace std ;
class Employee {
public:
// Constructor
Employee(const char* name, double salary) :
_name(name),
_salary(salary) {
}
// Accessors
const char* name() const {
return _name.c_str() ;
}
double salary() const {
return _salary ;
}
// Print functions
void businessCard(ostream& os = cout) const {
os << " +--------------------+ " << endl
<< " | ACME Corporation | " << endl
<< " +--------------------+ " << endl
<< " Name: " << name() << endl
<< " Salary: " << salary() << endl ;
}
private:
string _name ;
double _salary ;
} ;
class Manager : public Employee {
public:
//Constructor
Manager(const char* _name, double _salary):
Employee(_name, _salary),
_subordinates() {
}
// Accessors & modifiers
void addSubordinate(Employee& empl) {
_subordinates.insert(&empl);
}
const set<Employee*>& listOfSubordinates() const {
return _subordinates;
}
void businessCard(ostream& os = cout) const {
Employee::businessCard() ;
os << " Function: Manager" << endl ;
set<Employee*>::iterator iter ;
iter = _subordinates.begin() ;
os << " Subordinates:" << endl ;
if(_subordinates.empty()==true) {
os << " Nobody" << endl;
}
while(iter!=_subordinates.end()) {
os << " " << *iter << endl ; // <-- returns the memory location
++iter ;
}
}
private:
set<Employee*> _subordinates ;
} ;
#endif
主脚本
#include <string>
#include <iostream>
#include "Employee.hh"
using namespace std ;
int main() {
Employee emp1("David", 10000) ;
Employee emp2("Ivo", 9000) ;
Manager mgr1("Oscar", 18000) ; // Manager of Ivo and David
Manager mgr2("Jo", 14000) ;
Manager mgr3("Frank", 22000) ; // Manager of Jo and Oscar (and Ivo and David)
mgr1.addSubordinate(emp1) ;
mgr1.addSubordinate(emp2) ;
mgr3.addSubordinate(mgr1) ;
mgr3.addSubordinate(mgr2) ;
cout << '\n' ;
emp1.businessCard() ;
cout << '\n' ;
emp2.businessCard() ;
cout << '\n' ;
mgr1.businessCard() ;
cout << '\n' ;
mgr2.businessCard() ;
cout << '\n' ;
mgr3.businessCard() ;
cout << '\n' ;
return 0;
}
非常感谢任何帮助。
【问题讨论】:
-
不确定我是否正确理解了这个问题。你想取消引用迭代器
*iter? -
假设你有一个为
Employee定义的输出操作符写os << " " << *(*iter) << endl ; -
嗯,好的,我找到了迭代器,
*iter是迭代器引用的对象,因为这是一个指针,你需要*(*iter)来获取对象
标签: c++ pointers memory iterator