打分案例如下:
#include<iostream>
using namespace std;
#include<vector>
#include<deque>
#include<string>
#include<algorithm>
class student
{
public:
string name;
int mscore;
};
vector<student> s;
deque<int> a;
void createstudent(vector<student>&s)
{
string a = "abcde";
for (int i = 0; i < 5; i++)
{
student m;
m.name = "学生" + a[i];
m.mscore = 0;
s.push_back(m);
}
/*for (int i = 0; i < 5; i++)
{
student stu;
stu.name = "学生";
stu.name += a[i];
stu.mscore = 0;
s.push_back(stu);
}*/
}
void teacherset(deque<int>&a)
{
srand(time(0));
for (vector<student>::iterator it = s.begin(); it != s.end(); it++)
{
for (int i = 0; i < 10; i++)
{
int m = rand() % 100;
a.push_back(m);
}
sort(a.begin(), a.end());
a.pop_back();
a.pop_front();
int score = 0;
for (deque<int>::iterator it = a.begin(); it != a.end(); it++)
{
score += *it;
}
int meanscore = score / a.size();
it->mscore = meanscore;
}
}
bool compare(student& a, student& b)
{
return(a.mscore > b.mscore);
}
void printprize(vector<student>& a)
{
sort(a.begin(), a.end(), compare);
for (vector<student>::iterator it = a.begin(); it != a.end(); it++)
{
cout << "姓名:" << it->name << "成绩:" << it->mscore << endl;
}
}
void test() {
//创建学生
createstudent(s);
//老师打分
teacherset(a);
//打印排名
printprize(s);
}
int main()
{
test();
}
代码中:
for (int i = 0; i < 5; i++)
{
student m;
m.name = "学生" + a[i];
m.mscore = 0;
s.push_back(m);
}
产生的结果是
姓名:成绩:47
姓名:C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include\vector成绩:45
姓名:成绩:43
姓名:成绩:43
姓名::\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include\vector成绩:42
而将这段代码改成:
for (int i = 0; i < 5; i++)
{
student stu;
stu.name = "学生";
stu.name += a[i];
stu.mscore = 0;
s.push_back(stu);
}
程序才正常打印如下:
姓名:学生b成绩:55
姓名:学生d成绩:55
姓名:学生a成绩:54
姓名:学生e成绩:54
姓名:学生c成绩:53
问题:请问是什么原因造成打印C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include\vecto成这样,即姓名无法成功打印。直接(stu.name="学生"+a[i];)与(stu.name="学生";stu.name+=a[i];)有什么区别吗?会造成如此错误?