繁体   English   中英

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

[英]C++ : How to return the value the iterator of a set is pointing to?

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

我使用了一个类似的迭代器循环,之前它工作得很好,就像返回迭代器指向的值一样(对于双端队列和向量模板类)。

这个问题是对我今天早些时候遇到困难的脚本的跟进( C++:向集合中添加对象)。

该脚本现在如下所示:

头文件

#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()

那将是**iter ; 一个对迭代器的取消引用,一个对迭代器所引用的指针的引用。

暂无
暂无

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

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