zoukankan      html  css  js  c++  java
  • 10.3.4参数绑定 bind

        Count_if算法,类似find_if,此函数接受一对迭代器,表示一个输入范围,还接受一个谓词,会对输入范围中的每个元素执行。Count_if返回一个计数值,表示谓词有多少次为真。
        使用bind函数必须包含头文件functional且必须包含命名空间placeholders,该命名空间也包含于functional头文件中,所以使用此命名空间也必须包含此头文件, 如:
    using namespace (std::)placeholders;
    或 using (std::)placeholders::_1;  //名字_n都包含于命名空间placeholders
    vector<string>::iterator iter = find_if(words.begin(), words.end(),
    		bind(check_size, _1, sz));

    bind的参数个数:

    bind是可变参数的,他接受的第一个参数是一个可调用对象,级实际工作函数A,返回供算法使用的新的可调用对象B。若A接受x个参数,则bind的参数个数应该是x+1,即除了A外,其他参数应一一对应A所接受的参数。这些参数中有一部分来自B(_n),另外一些来自于所处函数的局部变量。
    下面是一个使用bind的例子

    #include <iostream>
    #include <string>
    #include <vector>
    #include <algorithm>
    #include <functional>
    
    using namespace std;
    using namespace placeholders;
    ostream &print(ostream &os, const string &s, char c);
    //using placeholders::_1;
    
    inline void output(vector<string> &words)
    {
    	for_each(words.begin(), words.end(), bind(print, ref(cout), _1, ' '));
    	cout << endl;
    }
    inline bool isShort(const string &a, const string &b)
    {
    	return a.size() < b.size();
    }
    
    ostream &print(ostream &os, const string &s, char c)
    {
    	return os << s << c;
    }
    inline bool check_size(const string &s, string::size_type sz)
    {
    	return s.size() >= sz;
    }
    void biggies(vector<string> &words, vector<string>::size_type sz)
    {
    	sort(words.begin(), words.end());
    	output(words);
    
    	auto it = unique(words.begin(), words.end());
    	output(words);
    
    	words.erase(it, words.end());
    	output(words);
    
    	stable_sort(words.begin(), words.end(), 
    		bind(isShort, _1, _2));
    	output(words);
    
    	vector<string>::iterator iter = stable_partition(words.begin(), words.end(),
    		bind(check_size, _1, sz));
    	output(words);
    
    	int count = iter - words.begin();
    	cout << "There is " << count << (count > 1 ? " words" : " word") 
    		<< " is 5 or longer." << endl;
    
    	for_each(words.begin(), iter, [](const string &s) { cout << s << " "; });
    	cout << endl;
    }
    int main()
    {
    	vector<string> words{ "the", "quick", "red", "fox", "jumps",
    		"over", "the", "slow", "red", "turtle" };
    	biggies(words, 5);
    	return 0;
    }
    
  • 相关阅读:
    tableView操作数据持久化
    9.0banb以前和9.0以后版本后JSON解析
    数据持久化存储回顾
    解决Xcode会出现的问题
    iview-cli 项目、iView admin 代理与跨域问题解决方案
    将变量做为一个对象的key,push新增进一个数组
    页面加载速度优化的建议
    vue中渲染页面,动态设置颜色
    e.currentTarget与e.target
    iview中tree的事件运用
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/12373473.html
Copyright © 2011-2022 走看看