列表指针类的输出向量

时间:2014-12-21 16:18:05

标签: c++ stl containers

这里很新。 需要从复杂的容器中输出值!! 课程如下。

class CourseClass
{
private:

    Professor* _professor;  // Profesor who teaches

    Course* _course; // Course to which class belongs

    list<StudentsGroup*> _groups; // Student groups who attend class

    int _numberOfSeats; // Number of seats (students) required in room

    bool _requiresLab; // Initicates wheather class requires computers

    int _duration; // Duration of class in hours

public:

    // Initializes class object
    CourseClass(Professor* professor, Course* course, const list<StudentsGroup*>& groups,
        bool requiresLab, int duration);
...
}

class Professor
{

private:

    int _id;  // Professor's ID

    string _name; //Professor Name

    list<CourseClass*> _courseClasses; // List of classes that professor teaches

public:
    // Initializes professor data
    Professor(int id, const string& name);
...
}

class Course
{
private:

    int _id; // Course ID

    string _name; // Course name

public:

    // Initializes course
    Course(int id, const string& name);
...
}

class StudentsGroup
{
private:

    int _id; // Student group ID

    string _name; // Name of student group

    int _numberOfStudents; // Number of students in group

    list<CourseClass*> _courseClasses; // List of classes that group attends

public:

    // Initializes student group data
    StudentsGroup(int id, const string& name, int numberOfStudents);

...
}

下面的矢量是我想要输出的,我将如何设计循环?

vector < list < CourseClass* > > _slots;

1 个答案:

答案 0 :(得分:2)

在c ++ 11中:

for(const auto& course_list : _slots)
{
  for(CourseClass* p: course_list)
  {
    do_something_with(*p);
    // or p->do_something();
  }
}

在c ++ 03中,它更乏味:

typedef list<CourseClass*> ClassList;
typedef vector<ClassList> ClassListVector;

ClassListVector::const_iterator slot = _slots.begin();
ClassListVector::const_iterator last_slot = _slots.end();
for( ; slot != last_slot ; ++slot)
{
  const ClassList& myClassList = *slot;
  ClassList::const_iterator class = myClassList.begin();
  ClassList::const_iterator class_end = myClassList.end();
  for( ; class != class_end ; ++class)
  {
    CourseClass* p = *class;
    do_something_with(p);
  }
}