this imp is using vector void addStudent(student g) { for(unsigned int i =0; i<n
ID: 3604359 • Letter: T
Question
this imp is using vector
void addStudent(student g)
{
for(unsigned int i =0; i<newStudent.size(); i++)
{
if(newStudent[i]== nullptr)
{
newStudent[i] =g;
break;
}
}
}
private:
std::vector<student> newSudent;
if you wanted to change it to std::map would this be the way to change it
void addStudent(std::string name, student g)
{
newStudent.insert(std::make_pair(name,g));
}
private:
std::map<std::string, student> newSudent;
need help.
Explanation / Answer
As we have a vector of pairs
name of the student is the key and student object will be the value in the map as
pair has first element as student name and second element as student object
so can copy the data from vector to a map with an insert iterator
Here goes the same code i am populating 3 student pairs into the vector
Hope this hepls you
std::vector<std::pair<std::string, int> > studentVector;
// here g means student object
studentVector.push_back(std::make_pair("Tom", g));
studentVector.push_back(std::make_pair("Allen", g));
studentVector.push_back(std::make_pair("Elf", g));
std::map<std::string, student> mapped_studentVector;
std::copy(studentVector.begin(), studentVector.end(),
std::inserter(mapped_studentVector, mapped_studentVector.begin()));
or you can straight away initialize the map like this
std::map<std::string, student> mapped_studentVector((studentVector.begin()), studentVector.end());
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.