> 文档中心 > 成长随心记15(c++常用算法,遍历,查找)

成长随心记15(c++常用算法,遍历,查找)

1,STL容器中常用的算法

1)遍历算法:for_each(beg,end,func)
解释:遍历容器内元素,func表示仿函数或者函数对象
例:
#include
#include

int arr[] = { 1,2,3,4,5 };
void print(int val) {
    cout << val;
}
void test1() {
    vector v(arr, arr + 5);
    for_each(v.begin(), v.end(), print);
}

2)遍历算法:transform(beg1,end1,beg2,func)
解释:beg1表示源容器开始迭代器,beg2表示转移目标容器,func表示仿函数或者函数对象
例:
#include
#include

int arr[] = { 1,2,3,4,5 };
class Transform {
public:
    int operator()(int val) {
        return val;
    }
};
void print(int val) {
    cout << val;
}
void test2() {
    vector v1(arr, arr + 5);
    vector v2;
    v2.resize(v1.size());//注意要重新指定新容器的大小
    transform(v1.begin(), v1.end(), v2.begin(),Transform());//搬运容器
    for_each(v2.begin(), v2.end(), print);//遍历容器
}

3)查找算法:find(beg,end,value)
解释:按值查找元素,找到了返回其位置迭代器,找不到返回结束迭代器

4)查找算法:adjacent_find(beg,end)
解释:查找相邻重复元素,返回相邻元素的第一个位置的迭代器 
例:
#include
#include
int main()
{
    int arr[] = { 1,4,5,5,2 };
    vectorv(arr, arr + 5);
    vector::iterator it = adjacent_find(v.begin(), v.end());
    if (it != v.end()) {
        cout << "Nice";
    }
    else
        cout << "Oh No";
}

5)查找算法:find_if(beg,end,pred)
解释:按值查找元素,找到了返回其位置迭代器,找不到返回结束迭代器,pred表示函数或者谓词
例:查找自定义数据类型
#include
#include

class person {
public:
    person(string name,int age):mname(name),mage(age){}
    string mname;
    int mage;
};
//class function {
//public:
//    bool operator()(person& p) {
//        return p.mage > 18;
//    }
//};
bool function(person &p){
    return p.mage > 18;
}
int main()
{
    person p1("a", 18);
    person p2("b", 20);
    person p3("c", 19);
    person arr[] = { p1,p2,p2 };
    vector v(arr, arr + 3);
    vector::iterator it=find_if(v.begin(), v.end(), function);//仿函数:function()
    if (it != v.end()) {
        cout << "找到了";
    }
}

6)查找算法:binary_search(beg,end,value)
解释:查找指定元素,查到返回TRUE,查不到返回FALSE
例:
#include
#include

int main()
{
    vectorv;
    for (int i = 0; i < 10; i++) {
        v.push_back(i);
    }
    if (binary_search(v.begin(), v.end(), 8)) {
        cout << "找到了";
    }
}

7)查找算法:count(beg,end,value)
解释:查找指定元素,返回value元素个数
例:
#include
#include

int main()
{
    int arr[] = { 1,2,3,5,2,5,3,6,7,9,2,2 };
    vector v(arr, arr + 12);
    cout<<count(v.begin(), v.end(), 2);
}

自定义数据类型需要重载==运算符
bool operator==(person s){
    if(name=s.name)
        return true;
    else
        return false;
}

8)查找算法:count_if(beg,end,pred)
解释:查找满足指定条件的元素个数,pred表示指定条件的谓词或者函数
例:
#include
#include
bool function(int val) {
    if (val > 2)
        return true;
    else
        return false;
}
int main()
{
    int arr[] = { 1,2,3,5,2,5,3,6,7,9,2,2 };
    vector v(arr, arr + 12);
    cout<<count_if(v.begin(), v.end(), function);
}