这似乎是一个学术问题,但我仍然对答案很感兴趣:
我有一个字符串向量s,我想在其中找到给定的字符串findme.这可以使用类似的东西来完成
find(s.begin(), s.end(), findme);
Run Code Online (Sandbox Code Playgroud)
我的问题是:必须有一种方法可以使用find_if和compareSTL字符串的方法作为谓词,但是如何?就像是
find_if(s.begin(), s.end(), bind2nd(mem_fun_ref(&string::compare), string("findme")) );
Run Code Online (Sandbox Code Playgroud)
不起作用,因为compare方法有几个重载,编译器不知道选择哪一个.
第二步:我使用find_if而不是find的动机是我有一个从具有字符串属性的类派生的对象向量,name我想找到一个具有给定名称的对象.这是可能的(没有编写额外的函数用作谓词)?
编辑:正如使用Boost提到的一些(大多数:)答案 - 我宁愿不必为此包含Boost.(据我所知,大多数Boost库都是"唯一"模板,因此应该有一种不使用Boost的方法.)
一种选择是将成员函数指针强制转换为合适的类型.你忘记的另一件事是std :: string :: compare对于相等的字符串返回0,所以你还需要否定functor.总而言之:
std::find_if(
vec.begin(), vec.end(),
std::not1(
std::bind2nd(
std::mem_fun_ref(static_cast<int (std::string::*)(const char*)const>(&std::string::compare)),
"findme"
)
)
);
Run Code Online (Sandbox Code Playgroud)
至于你对boost的理由:它的模板比STL函数头中的模板更灵活.它要么是提升,要么等待C++ 0x lambdas(我相信在这种情况下会是更好的方式)或者你自己写一些助手.目前它不能简单:
std::find_if(vec.begin(), vec.end(), boost::bind(&X::name, _1) == "findme");
Run Code Online (Sandbox Code Playgroud)
仅供参考,C++ 0x将添加std :: bind,类似于boost :: bind,但似乎重载operator ==的便利性不会出现.
| 归档时间: |
|
| 查看次数: |
9208 次 |
| 最近记录: |