zoukankan      html  css  js  c++  java
  • STL—常用遍历算法

    常用遍历算法

    学习目标:

    • 掌握常用的遍历算法

    算法简介:

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

    1 for_each

    功能描述:

    • 实现遍历容器

    函数原型:

    • for_each(iterator beg, iterator end, _func);

      // 遍历算法 遍历容器元素

      // beg 开始迭代器

      // end 结束迭代器

      // _func 函数或者函数对象

    示例:

    #include <algorithm>
    #include <vector>
    
    //普通函数
    void print01(int val) 
    {
    	cout << val << " ";
    }
    //函数对象
    class print02 
    {
     public:
    	void operator()(int val) 
    	{
    		cout << val << " ";
    	}
    };
    
    //for_each算法基本用法
    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(), print02());
    	cout << endl;
    }
    
    int main() {
    
    	test01();
    
    	system("pause");
    
    	return 0;
    }
    

    总结:for_each在实际开发中是最常用遍历算法,需要熟练掌握

    2 transform

    功能描述:

    • 搬运容器到另一个容器中

    函数原型:

    • transform(iterator beg1, iterator end1, iterator beg2, _func);

    //beg1 源容器开始迭代器

    //end1 源容器结束迭代器

    //beg2 目标容器开始迭代器

    //_func 函数或者函数对象

    示例:

    #include<vector>
    #include<algorithm>
    
    //常用遍历算法  搬运 transform
    
    class TransForm
    {
    public:
    	int operator()(int val)
    	{
    		return val;
    	}
    
    };
    
    class MyPrint
    {
    public:
    	void operator()(int val)
    	{
    		cout << val << " ";
    	}
    };
    
    void test01()
    {
    	vector<int>v;
    	for (int i = 0; i < 10; i++)
    	{
    		v.push_back(i);
    	}
    
    	vector<int>vTarget; //目标容器
    
    	vTarget.resize(v.size()); // 目标容器需要提前开辟空间
    
    	transform(v.begin(), v.end(), vTarget.begin(), TransForm());
    
    	for_each(vTarget.begin(), vTarget.end(), MyPrint());
    }
    
    int main() {
    
    	test01();
    
    	system("pause");
    
    	return 0;
    }
    

    总结: 搬运的目标容器必须要提前开辟空间,否则无法正常搬运

    吾生也有涯,而知也无涯
  • 相关阅读:
    新认识:SDF数据库
    捆绑(Bundle)
    VirtualBox-4.3.0启动报错及解决办法
    File.Exists(Application.StartupPath + \Settings\Settings.xml)
    C# [method Modifiers] abstract virtual override new
    360打补丁后系统无法启动的解决办法
    String.Compare 方法 (String, Int32, String, Int32, Int32)
    hdu4277 USACO ORZ
    Java实现 蓝桥杯 算法训练 最小乘积
    Java实现 蓝桥杯 算法训练 最小乘积
  • 原文地址:https://www.cnblogs.com/daimasanjiaomao/p/13977579.html
Copyright © 2011-2022 走看看