Could someone please verify. Is it proper to have pointers to containers(vectors in this example) where you allocate memory for them and then free them. I googled and found a posting that stated its considered poor coding style to do this...I doesn't seem like it should be poor programming style to me.
struct student contains the pointer
std::vector<double> *assignments;
Which I allocate in the program and then free towards the end with..
for (i = 0; i < the_students_size; ++i)
{
the_students.assignments->clear();
delete the_students.assignments;
}
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
//struct with pointer to vector....
struct student
{
std::string name;
double midterm, final;
std::vector<double> *assignments;
};
bool student_compare(const struct student & lhs, const struct student & rhs)
{
return lhs.name < rhs.name;
}
int main(int argc, char**argv)
{
struct student a_student;
std::vector<struct student> the_students;
int choice;
double x;
while (true)
{
std::cout<<"(0)exit (1)set (2)sort and view->";
std::cin>>choice;
if (choice < 1) break;
if (choice == 1)
{
a_student.assignments = new std::vector<double>;
if (!a_student.assignments) return 1;
std::cout<<"Please enter your name->";
std::cin>>a_student.name;
std::cout<<"enter midterm and final marks->";
std::cin>>a_student.midterm>>a_student.final;
std::cout<<"Please enter assignment marks "
"Eof file for completion"<<std::endl;
while (std::cin>>x)
a_student.assignments->push_back(x);
std::cin.clear();
the_students.push_back(a_student);
}
if (choice == 2)
{
std::vector<struct student>::const_iterator begin_iter = the_students.begin();
std::vector<struct student>::const_iterator end_iter = the_students.end();
std::sort(the_students.begin(), the_students.end(), student_compare);
while (begin_iter != end_iter)
{
std::cout<<"Name->"<<begin_iter->name<<std::endl;
std::cout<<"Midterm->"<<begin_iter->midterm<<" Final->"<<begin_iter->final<<std::endl;
std::vector<double>::const_iterator ibegin_iter = begin_iter->assignments->begin();
std::vector<double>::const_iterator iend_iter = begin_iter->assignments->end();
while (ibegin_iter != iend_iter)
{
std::cout<<*ibegin_iter<<" ";
++ibegin_iter;
}
std::cout<<std::endl;
++begin_iter;
}
}
}
std::vector<struct student>::size_type the_students_size = the_students.size();
std::vector<struct student>::size_type i = 0;
//delete assigment vectors...
for (i = 0; i < the_students_size; ++i)
{
the_students[i].assignments->clear();
delete the_students[i].assignments;
}
the_students.clear();
return 0;
}