#include <iostream>
#include <algorithm>
#include <forward_list>
#include<string>
#include<array>
#include<vector>
using namespace std;
struct people
{
int age;
string name;
string sex;
string strnum;
string straddr;
bool operator<(const people &p1)
{
return strnum < p1.strnum;
}
};
void main()
{
forward_list<people> m_forwardlist;
people m_p1;
m_p1.name = "ty1";
m_p1.age = 23;
m_p1.sex = "男";
m_p1.strnum = "12540112";
m_p1.straddr = "甘肅隴南康縣";
people m_p2;
m_p2.name = "ty2";
m_p2.age = 28;
m_p2.sex = "女";
m_p2.strnum = "12540118";
m_p2.straddr = "甘肅隴南康縣";
people m_p3;
m_p3.name = "ty3";
m_p3.age = 25;
m_p3.sex = "女";
m_p3.strnum = "12540111";
m_p3.straddr = "甘肅蘭州七里河";
m_forwardlist.push_front(m_p1);
m_forwardlist.push_front(m_p2);
m_forwardlist.push_front(m_p3);
int ncount = std::distance(m_forwardlist.begin(), m_forwardlist.end());
cout << "總數量:" << ncount << endl;
cout << "排序之前:\n";
for (auto p : m_forwardlist)
{
cout << p.name << "\t" << p.age << "\t" << p.sex << "\t" << p.straddr << "\t" << p.strnum << endl;
}
cout << "年齡排序:\n";
m_forwardlist.sort();
for (auto p : m_forwardlist)
{
cout << p.name << "\t" << p.age << "\t" << p.sex << "\t" << p.straddr << "\t" << p.strnum << endl;
}
people pfind;
pfind.strnum = "12540119";
//lower_bound:查找第一個大於或等於某個元素的位置, 函數lower_bound()在first和last中的前閉後開區間進行二分查找,
//返回大於或等於val的第一個元素位置(注意是地址)。如果所有元素都小於val,則返回last的位置
//upper_bound: 查找第一個大於某個元素的位置
auto it = lower_bound(m_forwardlist.begin(), m_forwardlist.end(), pfind);
if (it != m_forwardlist.end() && it->strnum == "12540118")
{
cout << it->name << "\t" << it->age << "\t" << it->sex << "\t" << it->straddr << "\t" << it->strnum << endl;
}
else
{
cout << "not find it\n";
}
m_forwardlist.remove_if([](const people &p){return p.strnum == "12540111"; });
cout << "刪除12540111:\n";
for (auto p : m_forwardlist)
{
cout << p.name << "\t" << p.age << "\t" << p.sex << "\t" << p.straddr << "\t" << p.strnum << endl;
}
forward_list<int> m_uqielist{ 1, 2, 3, 4, 5,6, 4, 3, 7, 9, 10, 12, 33,5 };
m_uqielist.sort();
for_each(m_uqielist.begin(), m_uqielist.end(), [](int a){cout << a << " "; });
cout << endl;
cout << "unique測試\n";
//去重功能(相鄰元素),所以得排序
m_uqielist.unique();
for_each(m_uqielist.begin(), m_uqielist.end(), [](int a){cout << a << " "; });
cout << endl;
int a[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 };
sort(a, a + 10);
for_each(a, a + 10, [](int x){cout << x << " "; }); cout << endl;
cout << "v:\n";
vector<int>v;
//將數組賦值給vector
v.assign(a, a + 10);
for (auto p:v)
{
cout << p << endl;
}
int d[10];
int b[5] = { 1, 3, 5, 7, 9 };
int c[5] = { 2, 4, 6, 8, 10 };
merge(b, b + 5, c, c + 5, d);
cout << "合成數組" << endl;
cout << "b:\n";
for_each(b, b + 5, [](int x){cout << x << " "; }); cout << endl;
cout << "c:\n";
for_each(c, c + 5, [](int x){cout << x << " "; }); cout << endl;
cout << "d:\n";
for_each(d, d + 10, [](int x){cout << x << " "; }); cout << endl;
system("pause");
}
運行結果: