STL——deque
程序员文章站
2024-02-12 22:20:22
...
中文名叫双端数组,就是比vector多了一个front操作 ,双口容器。
# include<iostream>
# include<algorithm>
# include<deque>
# include<string>
# include<vector>
# if 0
deque与vector的区别只是在于双口操作
# endif
using namespace std;
int arr[] = {5,1,2,3,4,7};
class Person{
public:
Person(){}
void setScore(int &s){this->score = s;}
void setName(string &s){this->name = s;}
public:
string name;
int score;
};
void printDeq(deque<int> deq)
{
for(int i = 0;i < deq.size();++i)
cout << deq[i] << " ";
cout << endl;
}
void test1()
{//初始化
deque<int> deq1;
deq1.assign(arr,arr+sizeof(arr)/sizeof(int));//赋值
printDeq(deq1);
deque<int> deq2(deq1);//deque(&deq)
printDeq(deq2);
deque<int> deq3(deq1.begin(),deq1.end());//deque(deq.beg,deq.end)//迭代器
printDeq(deq3);
deque<int> deq4(5,1);//deque(n,elem)
printDeq(deq4);
}
void test2()
{//赋值
deque<int> deq1;
deq1.assign(arr,arr+sizeof(arr)/sizeof(int));
printDeq(deq1);
deque<int> deq2;
deq2 = deq1;
printDeq(deq2);
deque<int> deq3;
deq3.assign(deq1.begin()+2,deq1.end());
printDeq(deq3);
}
void test3()
{//大小操作
deque<int> deq;
deq.assign(arr,arr+sizeof(arr)/sizeof(int));
cout << "size:" << deq.size() << endl;
if(!deq.empty())
printDeq(deq);
}
void test4()
{//存取操作
cout << "双端操作:" << endl;
deque<int> deq;
deque<int> deq1;
deq.assign(arr,arr+sizeof(arr)/sizeof(int));
deq1 = deq;
printDeq(deq);
int front = deq.front();
deq.pop_front();
int back = deq.back();
deq.pop_back();
cout << "front:" << front << " " << "back:" << back << endl;
cout << "去除首尾:" << endl;
printDeq(deq);
cout << "--------" << endl;
cout << "存取:" << endl;
for(int i = 0;i < deq1.size();++i)
cout << deq1[i] << " ";
}
void printV(vector<int> &v)
{
for(vector<int>::iterator it = v.begin();it != v.end();++it)
cout << *it << " ";
cout << endl;
}
bool cmp(int a,int b)
{
return a > b;
}
void getInfo(vector<Person> &v)
{
Person tmp;
string str;
int sum;
deque<int> deq;
vector<int> score;
int s;
for(int i = 0;i < 2;++i)
{
cout << "输入第"<< i+1 << "名选手名字:";
cin >> str;
tmp.setName(str);
//cout << tmp.name << endl;
cout << "输入评委打分:" << endl;
for(int i = 0;i < 10;++i)
{
cin >> s;
score.push_back(s);
}
sort(score.begin(),score.begin() + 10,cmp);//默认从小到大排序
for(int i = 0,j = 0;i < 10;++i)
deq.push_back(score[j++]);
deq.pop_front();
deq.pop_back();
printDeq(deq);
sum = 0;
for(int i = 0;i < deq.size();++i)
sum += deq[i];
//cout << "sum:" << sum << endl;
int average = (int)sum / deq.size();
tmp.setScore(average);
//cout << "average:" << average << endl;
v.push_back(tmp);
}
}
void printPerson(vector<Person> &v)
{
int i = 0;
for(vector<Person>::iterator it = v.begin();it != v.end();++it)
{
cout << "第" << i+1 << "名选手的名字:" << (*it).name << endl;
cout << "评分:" << (*it).score << endl;
}
}
void test5()
{
/*
*获取五个选手的十个评委打分,去除最高分,去除最低分,平均分
*/
vector<Person> v;
getInfo(v);
printPerson(v);
}
int main()
{
//test1();//初始化
//test2();//赋值
//test3();//大小操作
//test4();//存取,双端操作+存取操作符
test5();//案例
return 0;
}
运行结果:
test1:
test2:
test3:
test4:
test5:
上一篇: 递归斐波那契