STL常用遍历查找算法

# include <iostream>
# include <vector>
# include <algorithm>


/*
std::string sl = "hello";
std::transform(sl.begin(), sl.end(), sl.begin(), toupper);   


这样得到 sl 值是 (大写的) HELLO


transform 是遍历一个容器里面元素 然后执行一个操作
第1和2个参数是数据起始和结束位置(迭代器)
参数3是写入目标的起始位置
参数4是执行的操作(函数
*/


using namespace std;


//transform 将一个容器的元素 搬运 到另一个容器中
struct MyPlus
{
int operator()(int val)
{
return val + 100;
}
};


void MyPrint(int val)
{
cout << "val : " << val << endl; 
}
void test01()
{
vector<int> v1;
vector<int> v2;
//reserve就像荒地一样没有初始化不能直接用
//push_back是相当于初始化因为没有Push_back所以V2不能进行其它操作
for(int i = 0; i < 10; i++)
{
v1.push_back(i);
}
v2.resize(v1.size());//开辟空间
//transform 将一个容器的元素 搬运 到另一个容器中
transform(v1.begin(), v1.end(),v2.begin(), MyPlus());
for_each(v2.begin(), v2.end(), MyPrint);
}


//常用的查找算法
void test02()
{
vector<int> v1;
vector<int> v2;
for(int i = 0; i < 10; i++)
{
v1.push_back(i);
}
vector<int>::iterator ret = find(v1.begin(), v1.end(), 5);
if(ret == v1.end())
{
cout << "没有找到" << endl;
}
else
{
cout << "找到 :" << *ret << endl;
}
}


class Person
{
public:
Person(int age, int id):age(age), id(id){}
bool operator==(const Person p)
{
return p.id == this->id && p.age == this->age;
}
private:
int id;
int age;
};


void test03()
{
vector<Person> v1;
Person p1(10, 20), p2(20, 30);
v1.push_back(p1);
v1.push_back(p2);


vector<Person>::iterator ret = find(v1.begin(), v1.end(), p1);


if(ret == v1.end())
{
cout << "没有找到" << endl;
}
else
{
cout << "找到了" << endl; 
}
}


//binary_search 二分查找法
//注意: 在无序序列中不可用
//返回的是bool类型




bool MySearch(int val)
{
return val > 5;
}
bool MySearch2(int val)
{
return val > 5;
}
void test04()
{
vector<int> v1;
for(int i = 0; i < 10; i++)
{
v1.push_back(i);
}
v1.push_back(9);
bool ret = binary_search(v1.begin(), v1.end(), 5);
if(ret)
{
cout << "找到了" << endl;
}
else
{
cout << "没有找到!" << endl;
}
//adjacent_find找重复元素
vector<int>::iterator it = adjacent_find(v1.begin(), v1.end());

if(it != v1.end())
{
cout << "找到相邻重复元素" << endl;
}
else
{
cout << "没有找到相邻重复元素" << endl;
}
//find_if 会根据我们的条件返回第一个满足条件元素的迭代器
it = find_if(v1.begin(), v1.end(), MySearch);
if(it != v1.end())
{
cout << "找到了" << endl;
}
else
{
cout << "没有找到!" << endl;
}
//count//根据数字查找 count_if//根据条件查找
int num = count(v1.begin(), v1.end(), 9);
cout << "9出现的次数" << num << endl;
num = count_if(v1.begin(), v1.end(), MySearch2);
cout << "大于5的次数" << num << endl;
}


int main(int argc, char *argv[])
{
//test01();
//test02();
//test03();
test04();
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值