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;
    }
    
  • 相关阅读:
    .Net Core ----通过XUnit进行接口单元测试(带请求头及参数)并用output输出结果
    .Net Core---- 通过EPPlus批量导出
    .Net Core---- 自带Json返回日期带T格式 解决
    You need tcl 8.5 or newer in order to run the Redis test
    exec: "docker-proxy": executable file not found in $PATH
    docker 如何清理垃圾呢
    docker run 报错——WARNING: IPv4 forwarding is disabled. Networking will not work.
    go 依赖包管理工具gb安装报错
    keepalived实现nginx高可用
    php命令行查看扩展信息
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/12373473.html
Copyright © 2011-2022 走看看