gpt4 book ai didi

c++ - C++:如何返回集合的迭代器指向的值?

转载 作者:行者123 更新时间:2023-12-02 09:47:24 25 4
gpt4 key购买 nike

我从集合上的迭代器返回的值给出了内存位置而不是值。如何访问迭代器指向的元素?

我使用了类似的迭代器循环,在此之前效果很好,因为返回了迭代器指向的值(对于双端队列和 vector 模板类)。

这个问题是我今天早些时候遇到困难的脚本(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是地址,则此地址:*(*iter)*iter指向的值。

这应该在您的情况下有效:

while(iter != _subordinates.end()) 
{
os << " " << **iter << endl ; // <-- returns the value which is the set
++iter;
}

编辑:此问题已解决: (*iter)->name()

关于c++ - C++:如何返回集合的迭代器指向的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36959516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com