在小需求代码review中看到有对vector对象调用find_if函数,并通过bind2nd来帮顶一个自定义的一个比较器,用于在vector中查找符合特定条件的元素同过find_if返回元素的迭代器。于是上网找了一下关于find_if和bind2nd的用法,学习一下。
bind2nd和bind1nd
bind2nd和bind1nd是用于将二元运算转换为一元运算子,二者不同在于将要比较的值最为第一个参数传递还是第二个参数传递,详细的用法参见:
http://blog.csdn.net/simahao/article/details/405455
使用find_if和bind2nd按条件查找vector元素
/*************************************************************************
> File Name: vector_demo.cpp
> Author: sam.liux
> Mail: sam.liux@taobao.com
> Created Time: 2012骞湀11鏃熸湡鍥鏃垎54绉************************************************************************/
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<functional>
using namespace std;
struct compare: std::binary_function<string, char *, bool>
{
bool operator() (string & a, char* b) const
{
if (!a.compare(b))
return true;
else
return false;
}
};
void print_arr(vector<string> &vec){
vector<string>::iterator itr = vec.begin();
for (; itr!=vec.end(); itr++)
{
std::cout << *itr << std::endl;
}
}
int main()
{
string arr[]={"aa", "bb", "cc", "dd"};
vector<string> vec(arr, arr+4);
print_arr(vec);
std::vector<string>::iterator pos = std::find_if(vec.begin(), vec.end(),
std::bind2nd(compare(), "bb"));
std::cout << "found: " << *pos << std::endl;
std::cout << "erase element: " << "aa" << std::endl;
vec.erase(std::remove_if(vec.begin(), vec.end(),
std::bind2nd(compare(), "aa")));
print_arr(vec);
//std::cout << "the end is: " << *p << std::endl;
std::cout << "erase element: " << "bb" << std::endl;
vec.erase(std::remove_if(vec.begin(), vec.end(),
std::bind2nd(compare(), "bb")));
print_arr(vec);
//std::cout << "the end is: " << *pp << std::endl;
return 0;
}
configue.in:
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ(2.59)
AC_INIT(FULL-PACKAGE-NAME, VERSION, BUG-REPORT-ADDRESS)
AC_CONFIG_SRCDIR([bind2nd.cpp])
#AC_CONFIG_HEADER([config.h])
AM_INIT_AUTOMAKE
# Checks for programs.
AC_PROG_CXX
# Checks for libraries.
# Checks for header files.
# Checks for typedefs, structures, and compiler characteristics.
# Checks for library functions.
AC_OUTPUT([Makefile])
Makefile.am:
AUTOMAKE_OPTIONS=foreign
bin_PROGRAMS=bind2nd
bind2nd_SOURCES=bind2nd.cpp