deque容器类比vector容器来学习。
deque为双向开口容器,见下图。而对比vector容器作为单项开口容器,在头部插入与删除的操作效率奇差。
常用API应用学习 deque容器常用API
原理机制这里不深究,本章仅探讨如何使用deque。感兴趣的同学可以自己搜索,这里放一张原理图
#include
#include
using namespace std;
void printd(deque<int> &d)//打印函数(这里不需要引用&)
{
//法一
/*for (int i = 0; i < d.size(); i++)
{
cout << d[i] << " ";
}
cout << endl;*/
//法二
for (deque<int>::iterator it = d.begin(); it != d.end(); it++)
cout << *it << " ";//取*数据类型对应deque<>类型
cout << endl;
}
//deque容器构造(初始化)
void text01()
{
deque<int> d1;
deque<int> d2(10, 2);
deque<int> d3(d2.begin(), d2.end());
deque<int> d4(d3);
printd(d1);
printd(d2);
printd(d3);
printd(d4);
}
//deque容器赋值
void text02()
{
deque<int> d1;
deque<int> d2;
deque<int> d3;
d1.assign(10, 5);
d2.assign(d1.begin(), d1.end());//迭代器指定区间赋值
d3 = d2;//等号赋值
d1.swap(d2);//交换
if (d1.empty())
{
cout << "空" << endl;
}
else
{
cout << "size:" << d1.size() << endl;
}
d1.resize(5);//这里扔掉后五个元素
printd(d1);
}
//deque容器插入删除
void text03()
{
deque<int> d1;
d1.push_back(100);
d1.push_front(200);
d1.push_back(300);
d1.push_front(400);
printd(d1);
int val = d1.front();//拿到被删除的元素
d1.pop_front();//删除(无返回值)
val = d1.back();
d1.pop_back();
printd(d1);
}
int main()
{
cout << "\ntext01:\n";
text01();
cout << "\ntext02:\n";
text02();
cout << "\ntext03:\n";
text03();
return 0;
}
//创建5个选手,姓名得分,评委为其打分
#include
#include
#include
#include
#include
using namespace std;
class Player
{
public:
Player():name("no_name"),score(0) {}
Player(string name_,int score_):name(name_),score(score_){}
public:
string name;
int score;
};
//创建选手
void greate_play(vector<Player> &v)
{
string nameSeed = "ABCDE";
for (int i = 0; i < nameSeed.size(); i++)
{
Player p;
p.name = "选手";
p.name += nameSeed[i];
p.score = 0;
v.push_back(p);
}
}
//打分
void setScore(vector<Player> &v)
{
//打分
for (vector<Player>::iterator it = v.begin(); it != v.end(); it++)
{
deque<int> dscore;
for (int i = 0; i < 10; i++)
{
int score = rand() % 41 + 60;//60~100分
dscore.push_back(score);
}
//排序
sort(dscore.begin(), dscore.end());
//去掉最高分最低分
dscore.pop_front();
dscore.pop_back();
//求平均分
int totalScore = 0;
for (deque<int>::iterator dit = dscore.begin(); dit != dscore.end(); dit++)
{
totalScore += *dit;
}
int average = totalScore / dscore.size();
//保存分数
(*it).score = average;
}
}
bool cmp(Player a, Player b)
{
return a.score > b.score;
}
//排名
void printRank(vector<Player>& v)
{
sort(v.begin(), v.end(), cmp);
//打印
for (auto it = v.begin(); it != v.end(); it++)
{
cout << "name:" << (*it).name << "\t" << "score:" << (*it).score << endl;
}
}
int main()
{
//定义vector
vector<Player> p;
greate_play(p);
setScore(p);
printRank(p);
return 0;
}
谢谢阅读(〃’ ▽ '〃)如有纰漏欢迎指出,觉得还不错就点个赞吧。