常用遍历算法
for_each
示例
//普通函数
void printV(int val) {
cout << val << " ";
}
//仿函数
class PrintV {
public:
void operator()(int val) {
cout << val << " ";
}
};
void test01() {
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
使用普通函数
//for_each(v.begin(), v.end(), printV);
使用仿函数
for_each(v.begin(), v.end(), PrintV());
cout << endl;
}
transform
示例
class PrintV {
public:
void operator()(int val) {
cout << val << " ";
}
};
class Trans {
public:
int operator()(int val) {
return val * 2;
}
};
void test01() {
vector<int> v;
for (int i = 0; i < 5; i++) {
v.push_back(i);
}
//transform
vector<int> target;
//强调:目标容器需要提前 开辟空间!!
target.resize(v.size());
transform(v.begin(), v.end(), target.begin(), Trans());
//for_each
for_each(target.begin(), target.end(), PrintV());
cout << endl;
}
find
示例
class Person {
public:
Person() {}
Person(string name, int salary) {
this->pName = name;
this->pSalary = salary;
}
void printPerson() {
cout << "name: " << this->pName << " " << "salary: " << this->pSalary << endl;
}
bool operator==(const Person &p) {
if (this->pName == p.pName && this->pSalary == p.pSalary) {
return true;
}
else
{
return false;
}
}
string pName;
int pSalary;
};
class PrintV {
public:
void operator()(int val) {
cout << val << " ";
}
};
void test01() {
vector<int> v;
for (int i = 0; i < 5; i++) {
v.push_back(i);
}
//查找是否有5这个元素
vector<int>::iterator it=find(v.begin(), v.end(), 5);
if (it == v.end()) {
cout << "没找到" << endl;
}
else
{
cout << *it << endl;
}
//for_each
for_each(v.begin(), v.end(), PrintV());
cout << endl;
}
void test02(){
//找自定义的数据类型
vector<Person> v2;
Person p1("alex", 24);
Person p2("amy", 22);
Person p3("yum", 25);
Person p4("fred", 17);
Person p5("nod", 15);
v2.push_back(p1);
v2.push_back(p2);
v2.push_back(p3);
v2.push_back(p4);
v2.push_back(p5);
vector<Person>::iterator it=find(v2.begin(), v2.end(), p2);
//自定义数据类型进行对比时需要重载==,==的左右两端应该都是const
if (it == v2.end()) {
cout << "没找到" << endl;
}
else
{
(*it).printPerson();
}
}
常用查找算法
find_if
示例
class Person {
public:
Person(string name,int age) {
this->pName = name;
this->pAge = age;
}
string getPName() {
return this->pName;
}
void printPerson() {
cout << "name: " << this->pName;
cout << " Age: " << this->pAge;
}
private:
string pName;
int pAge;
};
class NamedLily {
public:
bool operator()(Person p) {
//仿函数,找到名为lily的人
return p.getPName() == "lily";
}
};
void test01() {
vector<Person> v;
v.push_back(Person("alex", 21));
v.push_back(Person("bob", 31));
v.push_back(Person("cristal", 18));
v.push_back(Person("lily", 24));
//find_if测试,返回迭代器对象
vector <Person>::iterator it=find_if(v.begin(), v.end(), NamedLily());
(*it).printPerson();
cout << endl;
}
adjacent_find(相邻、重复)
示例
void test01() {
vector<int> v;
v.push_back(10);
v.push_back(120);
v.push_back(20);
v.push_back(20);
v.push_back(10);
vector<int>::iterator it=adjacent_find(v.begin(), v.end());
cout << *it << endl;
}
binary_search(无序不可用)
示例
for (int i = 0; i < 10; i++) {
v.push_back(i);
}
bool ret = binary_search(v.begin(), v.end(), 9);
if (ret) {
cout << "found" << endl;
}
else {
cout << "not found" << endl;
}
count
count底层的比较是实现的,自定义数据类型需要重载
示例
bool operator ==(const Person &p) {
return this->getPAge() == p.pAge && this->getPName() == p.pName;
}
void test01() {
vector<Person> v;
v.push_back(Person("alex", 21));
v.push_back(Person("bill", 24));
v.push_back(Person("carry", 25));
v.push_back(Person("dot", 22));
v.push_back(Person("alex", 21));
Person p("alex", 21);
//统计自定义数据类型,比如找到和p年龄相同的人数,count底层的比较是==实现的,自定义数据类型需要重载==
int mycount=count(v.begin(), v.end(), p);
cout << mycount << endl;
}
count_if
示例
class AgeGreater30 {
public:
bool operator()(Person p) {
return p.getPAge() > 30;
}
};
void test01() {
vector<Person> v;
v.push_back(Person("alex", 21));
v.push_back(Person("bill", 24));
v.push_back(Person("carry", 21));
v.push_back(Person("dot", 22));
v.push_back(Person("alex", 21));
v.push_back(Person("king", 31));
v.push_back(Person("ivy", 43));
//count_if测试,第三个参数_pred同样是谓词
int mycount = count_if(v.begin(), v.end(), AgeGreater30());
cout << mycount << endl;
}
常用排序算法
sort
示例
class MyCompare {
public:
bool operator()(Person p1,Person p2) {
return p1.getPAge() > p2.getPAge();
}
};
void test01() {
vector<Person> v;
v.push_back(Person("alex", 21));
v.push_back(Person("bill", 24));
v.push_back(Person("carry", 21));
v.push_back(Person("dot", 22));
v.push_back(Person("alex", 21));
v.push_back(Person("king", 31));
v.push_back(Person("ivy", 43));
//sort算法,根据年龄降序
sort(v.begin(), v.end(), MyCompare());
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) {
(*it).printPerson();
cout << endl;
}
}
random_shuffle
示例
void test01() {
vector<Person> v;
v.push_back(Person("alex", 21));
v.push_back(Person("bill", 24));
v.push_back(Person("carry", 21));
v.push_back(Person("dot", 22));
v.push_back(Person("alex", 21));
v.push_back(Person("king", 31));
v.push_back(Person("ivy", 43));
//洗牌算法
/*sort(v.begin(), v.end(), MyCompare());*/
random_shuffle(v.begin(), v.end());
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) {
(*it).printPerson();
cout << endl;
}
}
merge
示例
void test01() {
vector<int> v1;
v1.push_back(2);
v1.push_back(3);
v1.push_back(1);
v1.push_back(5);
sort(v1.begin(), v1.end());
vector<int> v2;
v2.push_back(4);
v2.push_back(6);
v2.push_back(19);
v2.push_back(8);
sort(v2.begin(), v2.end());
//merge测试,参与merge的两个容器必须是有序的
vector<int> v3;
//需要提前分配内存
v3.resize(v1.size() + v2.size());
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
for (vector<int>::iterator it = v3.begin(); it != v3.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
reverse
void test02() {
vector<int> v1;
v1.push_back(2);
v1.push_back(3);
v1.push_back(1);
v1.push_back(5);
for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) {
cout << *it << " ";
}
cout << endl;
//reverse测试
reverse(v1.begin(), v1.end());
for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
常用拷贝替换算法
copy
示例
void test03() {
vector<Person> v;
v.push_back(Person("alex", 21));
v.push_back(Person("bob", 16));
vector<Person> v2;
//copy测试
v2.resize(v.size());
copy(v.begin(), v.end(), v2.begin());
for (vector<Person>::iterator it = v2.begin(); it != v2.end(); it++) {
(*it).printPerson();
}
}
replace
示例
void test04() {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(3);
v.push_back(5);
//replace测试
replace(v.begin(), v.end(), 3, 300);
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
replace_if
示例
void test05() {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(3);
v.push_back(5);
//replace_if测试,带if需要提供谓词
replace_if(v.begin(), v.end(), Greater2(), 100);
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
//replace_if的自定义数据类型测试
vector<Person> v2;
v2.push_back(Person("alex", 21));
v2.push_back(Person("king", 45));
v2.push_back(Person("jim", 10));
v2.push_back(Person("nod", 20));
replace_if(v2.begin(), v2.end(), AgeGreater20(), Person("person", 21));
for (vector<Person>::iterator it = v2.begin(); it != v2.end(); it++) {
(*it).printPerson();
}
}
swap
常用算术生成算法
accumulate
fill
常用集合算法
set_intersection(交集)
dst.resize(min(v1.size(), v2.size()));
示例
void myPrint(int val) {
cout << val << " ";
}
void test01() {
vector<int> v1;
vector<int> v2;
vector<int> dst;
for (int i = 0; i < 8; i++) {
v1.push_back(i);
}
for (int i = 2; i < 10; i++) {
v2.push_back(i);
}
cout << "v1.size: " << v1.size() << endl;
cout << "v2.size: " << v2.size() << endl;
dst.resize(v1.size() > v2.size() ? v2.size() : v1.size());
cout << "dst.size: " << dst.size() << endl;
//返回的是一个迭代器
vector<int>::iterator itEnd= set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), dst.begin());
for_each(dst.begin(), itEnd, myPrint);
cout << endl;
}
set_union(并集)
dst.resize(v1.size() + v2.size());
示例
vector<int>::iterator itEnd= set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), dst.begin());
set_difference(差集)
dst.resize(max(v1.size(), v2.size()));
示例
vector<int>::iterator itEnd= set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), dst.begin());
项目-演讲比赛流程管理系统
#include <iostream>
using namespace std;
#include<vector>
#include<deque>
#include<algorithm>
#include<functional>
#include<numeric>
#include<string>
class Person {
public:
Person(string name, double score) {
this->pName = name;
this->vScore = score;
}
Person() {}
string getPName() {
return this->pName;
}
int getVScore(){
return this->vScore;
}
void setVScore(double score) {
this->vScore = score;
}
void printPerson() {
cout << "name: " << this->pName;
cout << " score: " << this->vScore;
}
private:
string pName;
double vScore;
};
double score() {
deque<int> pScore;
int sco;
int avg;
for (int i = 0; i < 10; i++) {
sco = rand() % 41 + 60;
pScore.push_back(sco);
}
//掐头去尾
pScore.pop_back();
pScore.pop_front();
avg = accumulate(pScore.begin(), pScore.end(), 0)/pScore.size();
return avg;
}
class MyCompare {
public:
bool operator()(Person p1, Person p2) {
return p1.getVScore() > p2.getVScore();
}
};
void printPerson(vector<Person>& vp) {
//遍历vp,查看数据
for (vector<Person>::iterator it = vp.begin(); it != vp.end(); it++) {
(*it).printPerson();
cout << endl;
}
}
vector<Person> win(vector<Person> &vp) {
//首先按score排序
sort(vp.begin(), vp.end(), MyCompare());
//去掉最后三个
for (int i = 0; i < 3; i++) {
vp.pop_back();
}
return vp;
}
void test01() {
// 初始化12名选手
vector<Person> vp;
for (int i = 0; i < 12; i++) {
vp.push_back(Person("选手:" + to_string(i), score()));
}
//洗牌并分组
random_shuffle(vp.begin(),vp.end());
vector<Person> v1;
vector<Person> v2;
v1.resize(6);
v2.resize(6);
vector<Person>::iterator it;
copy(vp.begin(), vp.begin() + 6, v1.begin());
copy(vp.begin()+6, vp.end(), v2.begin());
if (v1.size() < 6 || v2.size() < 6) {
return;
}
//分组初赛
cout << "******************** 初赛 **************************" << endl;
vector<Person> win_vp1=win(v1);
cout << "************ win_vp1 **************" << endl;
printPerson(win_vp1);
vector<Person> win_vp2= win(v2);
cout << "************ win_vp2 **************" << endl;
printPerson(win_vp2);
//cout << "win_vp1.size: " << win_vp1.size() << endl;
//cout << "win_vp2.size: " << win_vp2.size() << endl;
//合并win_vp进行决赛
cout << "******************** 决赛 **************************" << endl;
vector<Person> final_vp;
for (vector<Person>::iterator it1 = win_vp1.begin(); it1 != win_vp1.end(); it1++) {
(*it1).setVScore(score());//决赛对每个选手进行打分
final_vp.push_back((*it1));
}
for (vector<Person>::iterator it2 = win_vp2.begin(); it2 != win_vp2.end(); it2++) {
(*it2).setVScore(score());//决赛对每个选手进行打分
final_vp.push_back((*it2));
}
vector<Person> final_win_vp = win(final_vp);
//cout << "final_vp.size: " << final_vp.size() << endl;
//cout << "final_win_vp.size: " << final_win_vp.size() << endl;
cout << "******************** 获胜的是: **************************" << endl;
printPerson(final_win_vp);
}
int main() {
//随机数种子
srand((unsigned int)time(NULL));
test01();
system("pause");
return 0;
}
课程中的示例
speechManager.h
#pragma once
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
#include<deque>
#include<numeric>
#include"speaker.h"
#include<fstream>
using namespace std;
//设计演讲管理类
class SpeechManager {
public:
SpeechManager();
~SpeechManager();
void showMenu();
void exitSys();
void initSpeech();
void createSpeaker();
void printSpeaker(map<int, Speaker> &m);
void stratSpeech();
void speechDraw();
void compete();
void showScore();
void saveRecord();
void loadRecord();
//比赛选手 容器 12人
vector<int> v1;
//第一轮晋级容器 6人
vector<int> v2;
//胜利前三名容器 3人
vector<int> vWin;
//存放编号以及对应选手的容器
map<int, Speaker> mSpeaker;
//记录比赛轮数
int m_Index;
//文件为空的标志
bool fileIsEmpty;
//往届记录
map<int, vector<string>> mRecord;
};
speechManager.cpp
#include"speechManager.h"
SpeechManager::SpeechManager() {
this->initSpeech();
this->createSpeaker();
this->printSpeaker(this->mSpeaker);
}
SpeechManager::~SpeechManager() {
}
void SpeechManager::showMenu() {
cout << "------------------------------------" << endl;
cout << "-------欢迎来到演讲比赛----------" << endl;
cout << "-------1、开始演讲比赛------------" << endl;
cout << "-------2、查看往届记录--------------" << endl;
cout << "-------3、清空比赛记录--------------" << endl;
cout << "-------4、退出比赛程序--------------" << endl;
cout << "------------------------------------" << endl;
cout << endl;
}
void SpeechManager::exitSys() {
cout << "感谢使用!" << endl;
system("pause");
exit(0);
}
void SpeechManager::initSpeech() {
this->v1.clear();
this->v2.clear();
this->vWin.clear();
this->mSpeaker.clear();
this->m_Index = 1;
}
void SpeechManager::createSpeaker() {
string nameSeed = "ABCDEFGHIJKL";
for (int i = 0; i < nameSeed.size(); i++) {
string name = "选手";
name += nameSeed[i];
Speaker sp;
sp.sName = name;
for (int j = 0; j < 2; j++) {
sp.sScore[j] = 0;
}
this->v1.push_back(i + 10001);
this->mSpeaker.insert(make_pair(i + 10001, sp));
}
}
void SpeechManager::printSpeaker(map<int, Speaker>& m)
{
for (map<int, Speaker>::iterator it = m.begin(); it != m.end(); it++) {
cout<<"编号: "<<(*it).first;
cout << " 姓名: " << (*it).second.sName;
cout << " 得分 " << (*it).second.sScore[0] << " " << (*it).second.sScore[1]<<endl;
}
}
void SpeechManager::stratSpeech()
{
//第一轮比赛
//1、抽签
speechDraw();
//2、比赛
compete();
//3、显示晋级结果
showScore();
//第二轮比赛
this->m_Index++;
//1、抽签
speechDraw();
//2、比赛
compete();
//3、显示最终分数
showScore();
//4、保存分数
saveRecord();
cout << "本届比赛结束" << endl;
system("pause");
system("cls");
}
void SpeechManager::speechDraw()
{
cout << "第" << this->m_Index << "轮比赛选手正在抽签" << endl;
cout << "*******************" << endl;
cout << "抽签后演讲顺序如下:" << endl;
if (this->m_Index == 1) {
random_shuffle(v1.begin(), v1.end());
cout << "第一轮抽签:" << endl;
for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) {
cout << *it << endl;
}
}
else
{
random_shuffle(v2.begin(), v2.end());
cout << "第二轮抽签:" << endl;
for (vector<int>::iterator it = v2.begin(); it != v2.end(); it++) {
cout << *it << endl;
}
}
cout << "**********************" << endl;
system("pause");
}
void SpeechManager::compete()
{
cout << "第" << this->m_Index << "轮比赛正式开始:**************" << endl;
multimap<double, int, greater<double>> groupScore;//临时容器,保存key分数 value 选手编号
int num = 0;//记录人员数,6个为1组
vector<int> v_Src;//比赛人员的容器
if (this->m_Index == 1) {
v_Src = v1;
}
else
{
v_Src = v2;
}
//遍历所有参赛选手
for (vector<int>::iterator it = v_Src.begin(); it != v_Src.end(); it++) {
num++;
//评委打分
deque<double> d;
for (int i = 0; i < 10; i++) {
double score = (rand() % 401 + 600) / 10.f;
d.push_back(score);
}
sort(d.begin(), d.end(), greater<double>());
d.pop_back();
d.pop_front();
//计算平均分
double avg=(accumulate(d.begin(),d.end(),0.0f))/(double)d.size();
this->mSpeaker[*it].sScore[this->m_Index - 1] = avg;
//6人一组,用临时容器保存
groupScore.insert(make_pair(avg, *it));
if (num % 6 == 0) {
cout << "第" << num / 6 << "小组的名次:" << endl;
for (multimap<double, int, greater<double>>::iterator it2 = groupScore.begin(); it2 != groupScore.end(); it2++) {
cout << "编号:" << (*it2).second << " 姓名: " << this->mSpeaker[(*it2).second].sName << " 成绩: " << this->mSpeaker[(*it2).second].sScore[this->m_Index - 1] << endl;
}
int count = 0;
//取前三名
for (multimap<double, int, greater<double>>::iterator it3 = groupScore.begin(); it3 != groupScore.end() && count < 3; it3++, count++) {
if (this->m_Index == 1) {
v2.push_back((*it3).second);
}
else
{
vWin.push_back((*it3).second);
}
}
groupScore.clear();
cout << endl;
}
}
cout << "第" << this->m_Index << "轮比赛结束***********" << endl;
system("pause");
}
void SpeechManager::showScore()
{
cout << "第" << this->m_Index << "轮晋级选手信息如下:" << endl;
vector<int> v;
if (this->m_Index == 1) {
v = v2;
}
else
{
v = vWin;
}
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << "编号:" << *it << " 姓名: " << this->mSpeaker[*it].sName << " 成绩: " << this->mSpeaker[*it].sScore[this->m_Index - 1] << endl;
}
cout << endl;
system("pause");
system("cls");
this->showMenu();
}
void SpeechManager::saveRecord()
{
ofstream ofs;
ofs.open("speech.csv", ios::out | ios::app);
//将获胜者每个人的数据写入文件中
for (vector<int>::iterator it = vWin.begin(); it != vWin.end(); it++) {
ofs << *it << "," << mSpeaker[*it].sScore[1] << ",";
}
ofs << endl;
ofs.close();
cout << "记录已保存" << endl;
}
void SpeechManager::loadRecord()
{
ifstream ifs("speech.csv", ios::in);
if (!ifs.is_open()) {
this->fileIsEmpty = true;
cout << "文件不存在!" << endl;
ifs.close();
return;
}
char ch;
ifs >> ch;
if (ifs.eof()) {
cout << "文件为空" << endl;
this->fileIsEmpty = true;
ifs.close();
return;
}
//文件不为空
this->fileIsEmpty = false;
ifs.putback(ch);//把读出来判断是否为空的那个字符放回去
string data;
int index;
while (ifs >> data) {
vector<string> v;
int pos = -1;
int start = 0;
while (true) {
pos = data.find(",", start);//从0开始找","
if (pos == -1) {
break;//找不到
}
string tmp = data.substr(start, pos - start);
v.push_back(tmp);
start = pos + 1;
}
this->mRecord.insert(make_pair(index, v));
index++;
}
cout << "往届信息已加载" << endl;
cout << data << endl;
ifs.close();
for (map<int, vector<string>>::iterator it = this->mRecord.begin(); it != this->mRecord.end(); it++) {
cout << (*it).first << " " << (*it).second[0] << " " << (*it).second[1] << endl;
}
}
main.cpp
#include<iostream>
#include"speechManager.h"
using namespace std;
int main() {
//随机数种子
srand((unsigned int)time);
SpeechManager sm;
int choice;
while (true) {
sm.showMenu();
cout << "请输入选择:" << endl;
cin >> choice;
switch (choice) {
case 1://开始比赛
sm.stratSpeech();
break;
case 2://查看记录
sm.loadRecord();
break;
case 3://清空记录
break;
case 4://退出系统
sm.exitSys();
break;
default:
system("cls");
break;
}
}
system("pause");
return 0;
}
speaker.h
#pragma once
#include<iostream>
using namespace std;
class Speaker {
public:
string sName;
double sScore[2];//保存初赛和决赛两轮的最终得分
};