- STL的常用算法
- 一、遍历
- 二、查找
- 2.1 find, find_if
- 2.2 adjacent_find
- 2.3 binary_search
- 2.4 count, count_if
- for_each
- transform
//遍历算法:for_each, transform
#include
#include
class Traversing
{
public:
void operator()(int v)
{
cout << v << " ";
}
};
class Transform
{
public:
int operator()(int v)
{
return v + 100;
}
};
void test()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i + 20);
}
//遍历vector容器 for_each
for_each(v.begin(), v.end(), Traversing()); //函数对象,Traversing()
cout << endl;
//transform遍历加转换
vector<int> v2;
v2.resize(10);
transform(v.begin(), v.end(), v2.begin(), Transform()); //函数对象,Transform()
for_each(v2.begin(), v2.end(), Traversing());
}
int main()
{
test();
return 0;
}
二、查找
- find find_if
- adjacent_find
- binary_search
- count count_if
//find 返回值是一个迭代器,如果没找到返回 .end()迭代器
//find_if 条件查找,同样返回一个迭代器,没找到就返回end()迭代器
#include
#include
class Person
{
public:
string name;
int age;
Person(string s, int a) : name(s), age(a) {}
bool operator==(const Person& p)
{
if (this->name == p.name && this->age == p.age)
{
return true;
}
else
{
return false;
}
}
};
class GreaterT
{
public:
bool operator()(Person& p)
{
return p.age > 25;
}
};
void test()
{
vector<Person> v;
Person p1("xwp", 26);
Person p2("yjj", 25);
Person p3("xxz", 21);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
Person p4("xwp", 18);
Person p5("yjj", 25);
vector<Person>::iterator it;
it = find(v.begin(), v.end(), p5); //find会对对象进行 == 判断,所以如果是自定义的类,需要重载 ==
if (it == v.end())
{
cout << "未找到\n";
}
else
{
cout << "找到了\n";
}
v.push_back(p4);
v.push_back(p5);
it = find_if(v.begin(), v.end(), GreaterT()); //Greater(),谓词
if (it == v.end())
{
cout << "未找到\n";
}
else
{
cout << "找到了 " << it->name << " " << it->age << endl;
}
}
int main()
{
test();
return 0;
}
2.2 adjacent_find
//adjacent_find
//查找相邻的重复元素,没找到返回迭代器end()
2.3 binary_search
//binary_search 二分查找,极快
//返回bool,只能用于有序序列
#include
#include
void test()
{
vector<int> v;
v.push_back(2);
v.push_back(3);
v.push_back(22);
v.push_back(11);
sort(v.begin(), v.end()); //排序
bool result = binary_search(v.begin(), v.end(), 11);
cout << result << endl;
}
int main()
{
test();
return 0;
}
2.4 count, count_if
//count 统计元素出现的次数
//count_if 按条件统计
#include
#include
class Greater23
{
public:
bool operator()(int val)
{
return val > 23;
}
};
void test()
{
vector<int> v;
v.push_back(20);
v.push_back(20);
v.push_back(30);
v.push_back(20);
v.push_back(25);
int result = count(v.begin(), v.end(), 20);
cout << "20出现的次数:" << result << endl;
int result2 = count_if(v.begin(), v.end(), Greater23());
cout << "大于23的数字个数:" << result2 << endl;
}
int main()
{
test();
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)