c+±基础知识-STL案例
1.vector deque应用
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <algorithm>
#include <ctime>
using namespace std;
class Person
{
public:
Person(string name,int score)
{
this->m_Name = name;
this->m_Score = score;
}
string m_Name;
int m_Score;
};
void createPerson(vector<Person> &v)
{
string name[] = {"A","B","C","D","E"};
int score = 0;
for (int i = 0; i < 5;i++)
{
Person p(name[i],score);
v.push_back(p);
}
}
void setScore(vector<Person> &v)
{
for(vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
deque<int>d;
for (int i = 0;i < 10; i++)
{
int score = rand()%41 + 60;
d.push_back(score);
}
sort(d.begin(),d.end());
d.pop_back();
d.pop_front();
int sum = 0;
int avg ;
for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++)
{
sum += *dit;
}
avg = sum/d.size();
(*it).m_Score = avg;
}
}
void showInfo(vector<Person> v)
{
for(vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
cout<<"姓名: "<<(*it).m_Name<<" 成绩: "<<(*it).m_Score<<endl;
}
}
void test()
{
srand((unsigned int)time(NULL));
vector<Person> v;
createPerson(v);
setScore(v);
showInfo(v);
}
int main()
{
test();
return 0;
}
2.vector map应用
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <map>
#include <algorithm>
#include <ctime>
using namespace std;
#define CEHUA 0
#define MEISHU 1
#define YANFA 2
class Worker
{
public:
Worker(string name,int salary)
{
this->m_Name = name;
this->m_Salary = salary;
}
string m_Name;
int m_Salary;
};
void createWorker(vector<Worker> &v)
{
string nameSeed[] = {"A","B","C","D","E","F","G","H","I","J"};
for (int i = 0; i < 10;i++)
{
int Salary = rand()%10000 + 10000;
Worker p(nameSeed[i],Salary);
v.push_back(p);
}
}
void setGroup(vector<Worker> &v, multimap<int,Worker> &mWorker)
{
for(vector<Worker>::iterator it = v.begin(); it != v.end(); it++)
{
int depthID = rand() % 3;
mWorker.insert(make_pair(depthID,*it));
}
}
void showWorkerByGroup(multimap<int,Worker>&m)
{
cout<<"策划部门: "<<endl;
multimap<int,Worker>::iterator pos = m.find(CEHUA);
int count = m.count(CEHUA);
int index = 0;
for (;pos != m.end()&&index <count;pos++,index++)
{
cout<<"姓名: "<<pos->second.m_Name<<" 薪水: "<<pos->second.m_Salary<<endl;
}
cout<<"美术部门: "<<endl;
multimap<int,Worker>::iterator pos1 = m.find(MEISHU);
int count1 = m.count(MEISHU);
int index1 = 0;
for (;pos1 != m.end()&&index <count1;pos1++,index1++)
{
cout<<"姓名: "<<pos1->second.m_Name<<" 薪水: "<<pos1->second.m_Salary<<endl;
}
cout<<"研发部门: "<<endl;
multimap<int,Worker>::iterator pos2 = m.find(YANFA);
int count2 = m.count(YANFA);
int index2 = 0;
for (;pos2 != m.end()&&index <count2;pos2++,index2++)
{
cout<<"姓名: "<<pos2->second.m_Name<<" 薪水: "<<pos2->second.m_Salary<<endl;
}
}
void test()
{
srand((unsigned int)time(NULL));
vector<Worker> vWorker;
createWorker(vWorker);
multimap<int,Worker>mWorker;
setGroup(vWorker,mWorker);
showWorkerByGroup(mWorker);
}
int main()
{
test();
return 0;
}