Two types of values ​​in one vector C ++

Say I have a vector for the Students class, but the question requirement is that I cannot map the class in the constructor, so I have to get around it.

Is it possible that I have two values ​​in one vector slot?

For example, the Student class and the string class are my arguments.

vector<Student*, string> Students;

So, at the end of the day, if I turn off the vector, I have to get Student AND grade in one slot.

It works? If so, how do I click_to calculate a value?

Otherwise, is there any other way to do this?

+4
source share
3 answers
std::vector<std::pair<Student*, string>> students;

or even better:

std::map<Student*, string> students;

Pressing Values:

first case:

students.push_back(std::make_pair(x,y));

even better (as reported by @snps):

students.emplace_back(x, y);

second case:

students[x]=y;

, Student*. , .

+7

.

. :

A1. :

class GradedStudent {
    Student body;
    string grade;
    public:
    GradedStudent(const string& grade);
    // reimplement all methods of `Student`, 
    // delegating implementations to `body`
};

std::vector<GradedStudent> gradedStudents;

2. ( ):

class Student {
public:
    Student();
};

class GradedStudent {
    string grade;
public:
    GradedStudent(const string& grade);
};

std::vector<GradedStudent*> gradedStudents;

A3. +   ( , - ):

class Student {
public:
    Student();
    virtual ~Student();
    virtual const string& getGrade() const { return ""; }
};

class GradedStudent : public IStudent {
    string grade;
public:
    GradedStudent(const string& grade);
    virtual string getGrade() const override { return grade; }
};

std::vector<Student*> students;
// non graded students will have empty string as a grade

. ( ):

std::vector<Student*> students;
std::vector<string> grades;

for(int i = 0; i < students.size(); ++i) {
    auto* student = students[i];
    auto grade = grades[i];
}

. ( "std::vector" ):

std::map<Student*, string> students;

for(auto student : students) {
    auto* student = student.first;
    auto grade = student.second;
}

. .

, .

P.S. ( )?

+2

Source: https://habr.com/ru/post/1623778/


All Articles