正确代码:
#include <iostream>
#include <vector>
#include <string>
//(1) 创建vector类型的容器,用于存放学生信息;
//
//(2) 创建3个学生(值自定义),放入向量中存储;
//
//(3) 编写函数计算所有学生的平均成绩;
//
//(4) 在向量中增加一个学生;
//
//(5) 从向量中删除第3个学生。
using namespace std;
struct stu
{
string name;
string sex;
string no;
float score;
}*student;
void creatVector(struct stu* student, vector <stu*>&pv);
void print_vector(vector<stu*> v);
float ave_score(vector<stu*>&pv);
int stu_num = 3;
vector <stu*> v ;
vector<stu*>* pv = &v;
int main()
{
creatVector(student,v);
print_vector(v);
cout << "学生成绩的平均值:" << ave_score(v) << endl;
}
void print_vector(vector<stu*> v)
{
for (vector<stu*>::iterator it = v.begin(); it != v.end(); it++)
{
cout << (*it)->name << "\t" << (*it)->no << "\t" << (*it)->score << "\t" << (*it)->sex << endl;
}
//cout << v[0]->name << " " << v[0]->no << " " << v[0]->score << v[0]->sex << endl;
}
void creatVector(struct stu* student, vector <stu*> &pv)
{
int stu_num = 3;
for (int i = 0; i < stu_num; i++)
{
stu* student = new stu();
cout << "输入姓名、性别、学号、成绩\n";
cin >> student->name >> student->sex >> student->no >> student->score;
pv.push_back(student);
}
}
float ave_score(vector<stu*>& pv)
{
float sum = 0;
float ave;
for (vector<stu*>::iterator it = pv.begin(); it != pv.end(); it++)
{
sum += (*it)->score;
}
ave = sum / pv.size();
return ave;
}
错误代码:
#include <iostream>
#include <vector>
#include <string>
//(1) 创建vector类型的容器,用于存放学生信息;
//
//(2) 创建3个学生(值自定义),放入向量中存储;
//
//(3) 编写函数计算所有学生的平均成绩;
//
//(4) 在向量中增加一个学生;
//
//(5) 从向量中删除第3个学生。
using namespace std;
struct stu
{
string name;
string sex;
string no;
float score;
}*student;
void print_vector(vector<stu*> v);
void creatVector(struct stu* student, vector<stu*> v );
vector <stu*> v;//WHY V[3] BUXING ???
int stu_num = 0;
int main()
{
creatVector(student,v);
print_vector(v);
}
void print_vector(vector<stu*> v)
{
for (vector<stu*>::iterator it = v.begin(); it != v.end(); it++)
{
cout << (*it)->name << "\t" << (*it)->no << "\t" << (*it)->score << "\t" << (*it)->sex << endl;
}
}
void creatVector(struct stu *student,vector<stu*> v)
{
student = new stu();
stu_num = 3;
for (int i = 0; i < stu_num; i++)
{
student->name = "name" + to_string(i);
student->no = to_string(i*111111111);
student->sex = "男";
student->score = i * 67;
v.push_back(student);
}
for (vector<stu*>::iterator it = v.begin(); it != v.end(); it++)
{
cout << (*it)->name << "\t" << (*it)->no << "\t" << (*it)->score << "\t" << (*it)->sex << endl;
}
}
错误显示:
这段代码中存在以下错误:
-
在
creatVector
函数中,student
是一个指针,但是在函数内部又被重新定义为一个stu
类型的对象。这会导致原来的指针丢失,无法正确访问到向量中的学生信息。 -
在
main
函数中,调用creatVector
函数时,传入的参数是student
和v
,但是student
并没有被初始化,它的值是不确定的。 -
在
creatVector
函数中,创建了一个新的stu
对象并赋值给student
,但是这个对象并没有被添加到向量中,所以向量中只有一个元素。 -
在
creatVector
函数中,使用了new
关键字来动态分配内存,但是没有使用delete
关键字来释放内存,这会导致内存泄漏。 -
在
print_vector
函数中,使用了迭代器来遍历向量,但是在循环体中又使用了箭头运算符来访问成员变量,这是不正确的
分析总结:
1.
2.