c++ stl 遍历算法和查找算法

news/2025/2/3 13:37:00 标签: c++, 算法, 开发语言

概述:

算法主要由头文件<algorithm> <functional> <numeric> 提供
<algorithm> 是所有 STL 头文件中最大的一个,提供了超过 90 个支持各种各样算法的函数,包括排序、合并、搜索、去重、分解、遍历、数值交换、拷贝和替换、插入和删除等
<functional> 定义了一些模板类,用以声明函数对象。函数对象(function object)是一个重载了函数调用操作符(operator())的类。
<numeric> 定义了执行算术运算的一些模板函数。

1. 常用遍历算法

学习目标:

掌握常用的遍历算法

算法简介:

for_each // 遍历容器
transform // 搬运容器到另一个容器中

1.1 for_each

函数原型

for_each(iterator beg, iterator end, _func) 
beg 起始迭代器
end 结束迭代器
_func 函数或者函数对象
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
using namespace std;

#define CEHUA 0
#define MEISHU 1
#define YANFA 2



//  普通函数
void print01(int val){
    cout << val << " ";
}

// 防函数
class PrintData{
public:
    void operator()(int val){
        cout << val << " ";
    }
};


void test01()
{
    // 逻辑非
    vector<int> v;
    for(int i = 0; i < 10; i++){
        v.push_back(i);
    }
    for_each(v.begin(), v.end(), print01);
    cout << endl;

    // 防函数
    for_each(v.begin(), v.end(), PrintData());
    cout << endl;

    // Lambda 表达式
    for_each(v.begin(), v.end(), [](int val){
        cout << val << " ";
    });
    cout << endl;
}

int main(int argc, char const *argv[])
{
    test01();
    return 0;
}

1.2 transform

概念:

搬运容器到另一个容器中

函数原型:

transform(iterator beg1, iterator end1, iteartor beg2, _fuc); 
beg1 原容器开始迭代器
end1 原容器结束迭代器
beg2 目标起始迭代器
_fuc 函数或者函数对象
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
using namespace std;

#define CEHUA 0
#define MEISHU 1
#define YANFA 2

//  stL 常用算法   transform

// transform(iterator beg1, iterator end1, iteartor beg2, _fuc); 

class Transform{
public:
    int operator()(int val){
        // 将数字翻倍
        return val * 2;
    }

};

void test01()
{
    vector<int> v;
    for (int i = 0; i < 10; i++){
        v.push_back(i);
    }

    vector<int> v2;
    v2.resize(v.size()); // 目标容器需要提前开辟空间
    transform(v.begin(), v.end(), v2.begin(),Transform());

    // 遍历容器
    for_each(v2.begin(), v2.end(), [](int val){
        cout << val << " ";
    });
}

int main(int argc, char const *argv[])
{
    test01();
    return 0;
}

2. 常用查找算法

算法简介

find  // 查找元素
find_if  // 按条件查找元素
adjacent_find  // 查找相邻重复元素
binary_search  // 二分查找
count  // 统计元素个数
count_if  // 按条件统计元素个数

2.1 find

查找指定元素,找到返回指定元素的迭代器,找不到返回end()

函数原型

find(begin, end, val) 
begin 开始迭代器
end 结束迭代器
val 查找的元素
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
using namespace std;

#define CEHUA 0
#define MEISHU 1
#define YANFA 2

//  stL 常用查找算法

// find 




// 查找内置的数据类型
void test01()
{
    vector<int> v;
    for (int i = 0; i < 10; i++)
    {
        v.push_back(i);
    }

    // 查找容器中是否有6
    vector<int>::iterator it = find(v.begin(), v.end(), 6);
    if(it == v.end()){
        cout << "没有找到" << endl;
    }
    else{
        cout << "找到元素为:" << *it << endl;
    }
    
}

// 查找自定义数据类型
class Person{
public:
    Person(string name, int age):m_Name(name),m_Age(age){}
    string m_Name;
    int m_Age;
	// 重载==
    bool operator==(const Person &p){
        if(this->m_Name == p.m_Name && this->m_Age == p.m_Age){
            return true;
        }
        else{
            return false;
        }
    }
};

void test02(){
    vector<Person> v;
    Person p1("西施", 18);
    Person p2("王昭君", 19);
    Person p3("杨玉环", 17);
    Person p4("貂蝉", 16);
    Person p5("小乔", 15);
    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);
    v.push_back(p4);
    v.push_back(p5);

    Person p("貂蝉", 16);

    vector<Person>::iterator it =  find(v.begin(), v.end(), p);
    if(it == v.end()){
        cout << "没有找到" << endl;
    }
    else{
        cout << "找到元素为:" << it->m_Name << " " << it->m_Age << endl;
    }
}

int main(int argc, char const *argv[])
{
    test02();
    return 0;
}

查找自定义数据,必须重载==

2.2 find_if

功能描述:

按条件查找元素

函数原型

find_if(iterator beg, iterator end, _Pred) 
功能描述:按条件查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
注意:_Pred为谓词(返回bool类型的防函数) 或 函数
beg 开始迭代器
end 结束迭代器
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
using namespace std;

#define CEHUA 0
#define MEISHU 1
#define YANFA 2

//  stL 常用查找算法

// find_if



// 查找内置的数据类型
void test01()
{
    vector<int> v;
    for (int i = 0; i < 10; i++)
    {
        v.push_back(i);
    }

    // 用lambda表达式实现 查找容器中是有大于6 
    vector<int>::iterator it = find_if(v.begin(), v.end(), [&](int val){
        return val > 6;
    });
    if(it == v.end()){
        cout << "没有找到" << endl;
    }
    else{
        cout << "找到元素为:" << *it << endl;
    }
    
}

// 查找自定义数据类型
class Person{
public:
    Person(string name, int age):m_Name(name),m_Age(age){}
    string m_Name;
    int m_Age;

    bool operator==(const Person &p){
        if(this->m_Name == p.m_Name && this->m_Age == p.m_Age){
            return true;
        }
        else{
            return false;
        }
    }
};

class findPerson{
public:
    bool operator()(const Person &p){
        // 查找年龄大于17的
        if (p.m_Age > 17)
        {
           return true;
        }
        else{
            return false;
        }
    }
};

void test02(){
    vector<Person> v;
    Person p1("西施", 18);
    Person p2("王昭君", 19);
    Person p3("杨玉环", 17);
    Person p4("貂蝉", 16);
    Person p5("小乔", 15);
    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);
    v.push_back(p4);
    v.push_back(p5);

    Person p("貂蝉", 16);

    vector<Person>::iterator it =  find_if(v.begin(), v.end(), findPerson());
    if(it == v.end()){
        cout << "没有找到" << endl;
    }
    else{
        cout << "找到元素为:" << it->m_Name << " " << it->m_Age << endl;
    }
}

int main(int argc, char const *argv[])
{
    test02();
    return 0;
}

2.3 adjacent_find

功能描述:

查找相邻重复元素

函数原型:

adjacent_find(iterator first, iterator last, binary_predicate pred);
功能描述:
查找相邻重复元素,返回相邻元素的第一个位置的迭代器
参数说明:
first:开始迭代器
last:结束迭代器
pred:二元谓词
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
using namespace std;

#define CEHUA 0
#define MEISHU 1
#define YANFA 2

//  stL 常用查找算法

// adjacent_find





// 查找内置的数据类型
void test01()
{
    vector<int> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(20);
    v.push_back(30);
    v.push_back(40);
    v.push_back(30);
    v.push_back(50);

    vector<int>::iterator it = adjacent_find(v.begin(), v.end());
    if (it == v.end()){
        cout << "找不到" << endl;
    }
    else{
        cout << "找到相邻重复元素为:" << *it << endl;
    }
    
}


// 查找自定义数据类型
class Person{
public:
    Person(string name, int age):m_Name(name),m_Age(age){}
    string m_Name;
    int m_Age;

    bool operator==(const Person &p){
        if(this->m_Name == p.m_Name && this->m_Age == p.m_Age){
            return true;
        }
        else{
            return false;
        }
    }
};

class findPerson{
public:
    bool operator()(const Person &p , const Person &p2){
        // 查找年龄相同的
        if (p.m_Age == p2.m_Age)
        {
           return true;
        }
        else{
            return false;
        }
    }
};

// 查找自定义数据类型
void test02(){
   vector<Person> v;
    Person p1("西施", 18);
    Person p2("王昭君", 19);
    Person p3("杨玉环", 19);
    Person p4("貂蝉", 16);
    Person p5("小乔", 15);
    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);
    v.push_back(p4);
    v.push_back(p5);


    vector<Person>::iterator it =  adjacent_find(v.begin(), v.end(), findPerson());
    if(it == v.end()){
        cout << "没有找到" << endl;
    }
    else{
        cout << "找到元素为:" << it->m_Name << " " << it->m_Age << endl;
    }
}

int main(int argc, char const *argv[])
{
    test02();
    return 0;
}

2.4 binary_search

查找指定元素是否存在

函数原型

bool binary_search(InputIterator first, InputIterator last, const T& val);

功能描述:

查找到val在[first, last)区间中,则返回true,否则返回false。
注意:在无序序列中不可用。
beg 开始迭代器
end 结束迭代器
val 查找的元素
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
using namespace std;

#define CEHUA 0
#define MEISHU 1
#define YANFA 2

//  binary_search


void test01()
{
    vector<int> v;
    for(int i = 0; i < 10; i++){
        v.push_back(i);
    }

    bool result = binary_search(v.begin(), v.end(), 10);
    if (result)
    {
        cout << "find" << endl;
    }
    else{
        cout << "not find" << endl;
    }
    
}



int main(int argc, char const *argv[])
{
    test01();
    return 0;
}

2.5 count

功能描述:

统计元素个数

函数原型

count(InputIterator first, InputIterator last, const T& val);

功能描述:

统计出元素次数
beg 开始迭代器
end 结束迭代器
val 查找的元素
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
using namespace std;

#define CEHUA 0
#define MEISHU 1
#define YANFA 2

//  count

// 统计内置数据类型
void test01()
{
    vector<int> v;
    for(int i = 0; i < 10; i++){
        v.push_back(i);
    }
    v.push_back(10);
    v.push_back(10);

    int result = count(v.begin(), v.end(), 10);
    cout << result << endl;

    
}

// 统计自定义数据类型
class Person{
public:
    Person(string name, int age):m_Name(name), m_Age(age){}
    
    bool operator==(const Person &p){
        if(this->m_Age == p.m_Age){
            return true;
        }
        else{
            return false;
        }
    }
    string m_Name;
    int m_Age;
};

void test02(){
    vector<Person> v;
    v.push_back(Person("西施", 18));
    v.push_back(Person("小龙女", 18));
    v.push_back(Person("貂蝉", 20));
    v.push_back(Person("杨玉环", 18));
    v.push_back(Person("王昭君", 19));

    Person p("小乔",18);

    int result = count(v.begin(), v.end(), p);
    cout << "和小乔年龄相同的人有" << result << "个";
}


int main(int argc, char const *argv[])
{
    test02();
    return 0;
}

总结:统计自定义类型的时候,需要重载 operator==

2.6 count_if

功能描述: 按照条件在容器中统计元素个数

函数原型:

count_if(iterator beg, iterator end, _Pred)
beg 开始迭代器
end 结束迭代器
_Pred 谓词
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;

#define CEHUA 0
#define MEISHU 1
#define YANFA 2

//   count_if

class Greater{
public:
    Greater(int val):m_Val(val){}
    bool operator()(int val){
        return val > m_Val;
    }
    int m_Val; // 可以改变条件
};

// 统计内置数据类型
void test01()
{
    vector<int> v;
    for(int i = 0; i < 10; i++){
        v.push_back(i);
    }
    v.push_back(10);
    v.push_back(10);
    // 统计大于8的数字有多少个
    int result = count_if(v.begin(), v.end(), Greater(8));
    cout << result << endl;
}

// 统计自定义数据类型
class Person{
public:
    Person(string name, int age):m_Name(name), m_Age(age){}

    bool operator==(const Person &p){
        if(this->m_Age == p.m_Age){
            return true;
        }
        else{
            return false;
        }
    }
    string m_Name;
    int m_Age;
};


class CountPerson{
public:
    CountPerson(int age):m_Age(age){}
    bool operator()(const Person &p){
        return p.m_Age > m_Age;
    }
    int m_Age;
};

void test02(){
    vector<Person> v;
    v.push_back(Person("西施", 18));
    v.push_back(Person("小龙女", 18));
    v.push_back(Person("貂蝉", 20));
    v.push_back(Person("杨玉环", 18));
    v.push_back(Person("王昭君", 19));
    Person p("小乔",18);
    v.push_back(p);

    int result = count_if(v.begin(), v.end(), CountPerson(17));
    cout << "年龄大于17的美女: " << result << "个";
}


int main(int argc, char const *argv[])
{
    test02();
    return 0;
}


http://www.niftyadmin.cn/n/5840849.html

相关文章

网站快速收录:利用网站导航优化用户体验

本文转自&#xff1a;百万收录网 原文链接&#xff1a;https://www.baiwanshoulu.com/44.html 网站快速收录与用户体验的提升密切相关&#xff0c;而网站导航作为用户访问网站的“指南针”&#xff0c;其优化对于实现这一目标至关重要。以下是一些利用网站导航优化用户体验&am…

面试题:React实现鼠标托转文字绕原点旋转

} componentDidMount() { document.onmousemove (e) > { if (this.state.moveFlag) { let {pageX, pageY} e; // 1. 更改矩形位置 if (this.state.moveFlag) { this.setState({ left: pageX - 25, top: pageY - 10 }) } // 2. 清空画布并绘制新的线 this._cl…

Ubuntu 下 nginx-1.24.0 源码分析 - ngx_strerror_init()函数

目录 ngx_strerror_init()函数声明 ngx_int_t 类型声明定义 intptr_t 类型 ngx_strerror_init()函数实现 NGX_HAVE_STRERRORDESC_NP ngx_strerror_init()函数声明 在 nginx.c 的开头引入了: #include <ngx_core.h> 在 ngx_core.h 中引入了 #include <ngx_er…

【回溯+剪枝】回溯算法的概念 全排列问题

文章目录 46. 全排列Ⅰ. 什么是回溯算法❓❓❓Ⅱ. 回溯算法的应用1、组合问题2、排列问题3、子集问题 Ⅲ. 解题思路&#xff1a;回溯 剪枝 46. 全排列 46. 全排列 ​ 给定一个不含重复数字的数组 nums &#xff0c;返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。 …

HTB:Alert[WriteUP]

目录 连接至HTB服务器并启动靶机 信息收集 使用rustscan对靶机TCP端口进行开放扫描 使用nmap对靶机TCP开放端口进行脚本、服务扫描 使用nmap对靶机TCP开放端口进行漏洞、系统扫描 使用nmap对靶机常用UDP端口进行开放扫描 使用ffuf对alert.htb域名进行子域名FUZZ 使用go…

pytorch基于GloVe实现的词嵌入

PyTorch 实现 GloVe&#xff08;Global Vectors for Word Representation&#xff09; 的完整代码&#xff0c;使用 中文语料 进行训练&#xff0c;包括 共现矩阵构建、模型定义、训练和测试。 1. GloVe 介绍 基于词的共现信息&#xff08;不像 Word2Vec 使用滑动窗口预测&…

C++ 哈希封装详解

文章目录 1.buckets1.1 load_factor和max_load_factor1.2 reserve和rehash1.3 bucket_count1.4 bucket_size 2.哈希表的底层2.1 iterator的实现2.2 operator2.3 HashTable.h2.4 Unorderedmap.h2.5 Uorderedset.h 1.buckets 1.1 load_factor和max_load_factor load_factor负载…

JavaScript系列(54)--性能优化技术详解

JavaScript性能优化技术详解 ⚡ 今天&#xff0c;让我们继续深入研究JavaScript的性能优化技术。掌握这些技术对于构建高性能的JavaScript应用至关重要。 性能优化基础概念 &#x1f3af; &#x1f4a1; 小知识&#xff1a;JavaScript性能优化涉及多个方面&#xff0c;包括代…