zoukankan      html  css  js  c++  java
  • stl中的for_each() 函数的注意事项

    #include<iostream>
    using namespace std;
    #include"vector"
    #include"algorithm"
    //
    void PrintV(vector <int > &temp)
    {
    	for (vector<int>::iterator it = temp.begin(); it != temp.end(); it++)
    	{
    		cout << *it << " ";
    	}
    	cout << endl;
    }
    void showV(int &n)
    {
    	cout << n << " ";
    }
    class C_showV
    {
    public:
    	void operator() (int &n)
    	{
    		cout << n << " ";
    	}
    protected:
    private:
    
    };
    class C_showV2
    {
    public:
    	C_showV2()
    	{
    		this->num = 0;
    	}
    	void operator() (int &n)
    	{
    		num++;
    		cout << n << " ";
    	}
    	void PrintN()
    	{
    		cout << num << endl;
    	}
    protected:
    private:
    	int num;
    };
    int main()
    {
    	vector <int> v1;
    	v1.push_back(1);
    	v1.push_back(6);
    	v1.push_back(3);
    	v1.push_back(18);
    	cout << "PrintV(v1) +++++> ";
    	PrintV(v1);
    	cout << endl;
    	cout << "运用回调函数入口实现:for_each(v1.begin(), v1.end(),showV )+++++> ";
    	for_each(v1.begin(), v1.end(),showV );
    	cout << endl;
    	cout << "运用函数对象入口实现:for_each(v1.begin(), v1.end(),C_showV())+++++> ";
    	for_each(v1.begin(), v1.end(), C_showV());
    	cout << "
    我是漂亮的分割线,接下来针对于函数对象的几种情况:
    ";
    
    	C_showV2 tem1 = for_each(v1.begin(), v1.end(), C_showV2());
    	cout << endl;
    	tem1.PrintN();//4
    
    	C_showV2 tem2;
    	C_showV2 tem11 = for_each(v1.begin(), v1.end(), tem2); // 初始化
    	cout << endl;
    	tem11.PrintN(); //4
    	tem2.PrintN();// 0 tem2和tem1的值不相同的主要原因是实参和形参,在加上for_each的定义是元素 不是引用。
    
    
    	tem11 = for_each(v1.begin(), v1.end(), tem2);//赋值
    	cout << endl;
    	tem11.PrintN();//4
    	system("pause");
    }
    
    •   初始化的赋值的异同
    • 形参和实参赋值的异同
  • 相关阅读:
    12.14 Daily Scrum
    12.13 Daily Scrum
    12.12 Daily Scrum
    12.11 Daily Scrum
    12.10 Daily Scrum
    12.9 Daily Scrum
    12.8 Daily Scrum
    M1事后分析汇报以及总结
    alpa开发阶段团队贡献分
    第9周团队作业
  • 原文地址:https://www.cnblogs.com/xiaochige/p/6959129.html
Copyright © 2011-2022 走看看