C++提高 STL
这一章节的内容大部分都是记忆接口。
随机数种子 rand
ctime
评委打分案例
class Person
{
public:
Person(string n,int a)
{
this->name=n;
score=a;
}
string name;
int score;
};
void create(vector<Person>&v)
{
string nameseed="ABCDE";
for(int i=0;i<5;i++)
{
string tempname="选手";
tempname+=nameseed[i];
int tempscore=0;
Person p(tempname,tempscore);
v.push_back(p);
}
}
void setscore(vector<Person>&v)
{
for(int i=0;i<v.size();i++)
{
deque<int>q;
for(int j=0;j<10;j++)
{
int score=rand()%41+60;
q.push_back(score);
}
sort(q.begin(),q.end());
q.pop_front();q.pop_back();
int sum=0;
for(int j=0;j<8;j++)
{
sum+=q[j];
}
int avg=sum/8;
v[i].score=avg;
}
}
void test()
{
vector<Person>v;
create(v);
setscore(v);
for(int i=0;i<5;i++)
{
cout<<v[i].name<<" "<<v[i].score<<endl;
}
}
int main()
{
srand((unsigned int)time(NULL));
test();
system("pause");
return 0;
}
员工分组案例
#define CEHUA 0
#define MEISHU 1
#define YANFA 2
class worker
{
public:
string name;
int salary;
};
void create(vector<worker>&v)
{
string nameseed= "ABCDEFGHIJ";
for(int i=0;i<10;i++)
{
string name="员工";
name+=nameseed[i];
worker w;
w.name=name;
w.salary=rand()%10000+10000;
v.push_back(w);
}
}
void setGroup(vector<worker>&v,multimap<int,worker>&m)
{
for(vector<worker>::iterator it=v.begin();it!=v.end();it++)
{
int depid=rand()%3;
m.insert(make_pair(depid,*it));
}
}
void showGroup(vector<worker>&v,multimap<int,worker>&m)
{
cout << "策划部门:" << endl;
multimap<int,worker>::iterator pos=m.find(CEHUA);
int cnt=m.count(CEHUA);
int index=0;
for(;pos!=m.end()&&index<cnt;pos++,index++)
{
cout<<"姓名: "<<pos->second.name<<" 工资: "<<pos->second.salary<<endl;
}
cout << "----------------------" << endl;
cout << "美术部门: " << endl;
pos=m.find(MEISHU);
cnt=m.count(MEISHU);
index=0;
for(;pos!=m.end()&&index<cnt;pos++,index++)
{
cout<<"姓名: "<<pos->second.name<<" 工资: "<<pos->second.salary<<endl;
}
cout << "----------------------" << endl;
cout << "研发部门: " << endl;
pos=m.find(YANFA);
cnt=m.count(YANFA);
index=0;
for(;pos!=m.end()&&index<cnt;pos++,index++)
{
cout<<"姓名: "<<pos->second.name<<" 工资: "<<pos->second.salary<<endl;
}
}
void test()
{
vector<worker>v;
create(v);
multimap<int,worker>m;
setGroup(v,m);
showGroup(v,m);
}
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果