与前面只有结构体的name声明不同,初始化不同!!
// Practice3_vector_sort_struct.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iostream>
#include <ctime>
#include <stdio.h>
#include <string>
using namespace std;
struct ScoreStruct
{
char name[32]; //和上个例子不同,这里声明由string name改为char name[32]
unsigned int score;
bool operator <(const ScoreStruct &right) const
{
return score < right.score;
}
};
void initVector(vector<ScoreStruct> &vec, unsigned int size)
{
srand(unsigned(time(NULL)));
for(unsigned int i =0; i < size; i++)
{
char buff[32] = {0};
int randNum = rand()%100;
sprintf(buff, "%d", randNum);
//ScoreStruct ss = {buff, randNum};//声明改了,此句不再能初始化,改为下面初始化
ScoreStruct ss = {"0", 0};
strcpy(ss.name, buff);// ss.name = buff,这样不能正常工作!!为何??
ss.score = randNum;
vec.push_back(ss);
}
}
void printVector(vector<ScoreStruct> vec)
{
vector<ScoreStruct>::iterator it = vec.begin();
for(; it != vec.end();++it)
{
//cout << it->name << "," << it->score << " ";//声明由string name改为char name[32],此句仍然可以工作
printf("%d,", it->score);
printf("%s
", it->name);//声明由string name改为char name[32],此句可以工作了,printf打印字符串必须是首地址,printf必须是纯C,string是C++,所以不行
}
cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<ScoreStruct> vect;
initVector(vect, 4);
cout<<"before sort"<<endl;
printVector(vect);
sort(vect.begin(), vect.end());
cout<<"after sort"<<endl;
printVector(vect);
return 0;
}
printf