C++ 容器操作數據何其粗暴!基礎案例排序,遍歷為例

聲明:此文並未使用C++11標準,圖片隨便選擇一張,不喜勿擾,C++11文章請轉接其他文章。

C++ 容器操作數據何其粗暴!基礎案例排序,遍歷為例,老鳥勿嘲,不喜勿噴。

主要代碼

C++ 容器操作數據何其粗暴!基礎案例排序,遍歷為例

更多精彩關注,持續更新,私信“代碼” 海量學習資料

主函數

C++ 容器操作數據何其粗暴!基礎案例排序,遍歷為例

更多精彩關注,持續更新,私信“代碼” 海量學習資料

運行結果

C++ 容器操作數據何其粗暴!基礎案例排序,遍歷為例

更多精彩關注,持續更新,私信“代碼” 海量學習資料

代碼(更多精彩關注,持續更新,)

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

#include <functional>

using namespace std;

struct student

{

string name;

int english;

int math;

}stuArray[3] = { "su", 0, 138, "天王", 110, 59, "承諾", 100, 100 };

bool compareByName(student first, student second)

{

return first.name<second.name>

}

bool compareByMath(student first, student second)

{

return first.math<second.math>

}

bool compareByEnglish(student first, student second)

{

return first.english<second.english>

}

ostream& operator<

{

out << data.name << "\t" << data.english << "\t" << data.math << endl;

return out;

}

template <typename>

void print(T data)

{

cout << data;

}

//仿函數:類的對象能行使函數功能

//調用和普通函數一樣

//類的要求:必須重載()

class Func

{

public:

//內部功能自己決定

void operator()(const string& str) const

{

cout << str << endl;

}

};

int main()

{

vector<student> myvector;/<student>

myvector.assign(stuArray, stuArray + 3);

for_each(myvector.begin(), myvector.end(), print<student>);/<student>

cout << "sort by name:" << endl;

sort(myvector.begin(), myvector.end(), compareByName);

for_each(myvector.begin(), myvector.end(), print<student>);/<student>

cout << "sort by math:" << endl;

sort(myvector.begin(), myvector.end(), compareByMath);

for_each(myvector.begin(), myvector.end(), print<student>);/<student>

cout << "sort by enlgish:" << endl;

sort(myvector.begin(), myvector.end(), compareByEnglish);

for_each(myvector.begin(), myvector.end(), print<student>);/<student>

cout << endl;

system("pause");

return 0;

}

/<second.english>

/<second.math>

/<second.name>


分享到:


相關文章: