c++ - 列表指针类的输出 vector

标签 c++ stl containers

我是新来的。 需要从一个复杂的容器输出值!! 这些类(class)如下。

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是我要输出的,我要怎么设计循环?

vector < list < CourseClass* > > _slots;

最佳答案

在 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);
  }
}

关于c++ - 列表指针类的输出 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27591248/

相关文章:

c++ - Intel Realsense 的等效传感器是什么

c++ - 如何初始化STL容器中存在的类的数据?

c++ - 为什么很多 Allocator 函数是可选的?

c++ - STL 映射类数据结构,允许基于两个键进行搜索

c++ - std::scoped_allocator_adaptor 的目的是什么?

c++ - 在 C++ 中设置一个(short int)的高字节和低字节

c++ - 在 C++ 中检测对象何时传递给新线程?

java - std::make_heap 等同于 Java?

docker - Bluemix 无法连接或 ping 到容器

image - 使用docker-compose创建容器会删除另一个已经运行的容器