我需要找到一个在地图中显示的向量元素。困难的部分是向量由结构组成,因此您应该首先调用成员函数从结构中提取值,以将其与地图元素进行比较。
所以,对于循环而言,它非常简单:
vector<A>::iterator it;
for( it = vec.begin(); it != vec.end(); ++it )
{
if( mp.count( it->getKey() ) )
{
break;
}
}
我的问题:有没有办法在一行中完成,比如
//this doesn't work as count accepts key_type
vector<A>::iterator it = find_if( vec.begin(), vec.end(), boost::bind( &map<string, string>::count, mp, boost::bind( &A::getKey, _1 ) )) != 0);
完整示例,测试
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/assign.hpp>
using namespace std;
class A{
public:
A( const std::string& key )
: key( key ) {}
std::string getKey(){ return key; }
private:
std::string key;
};
int main(int argc, const char *argv[]) {
map<string, string> mp = boost::assign::map_list_of( "Key1", "Val1" ) ( "Key2", "Val2" ) ( "Key3", "Val3" );
vector<A> vec = boost::assign::list_of( "AAA" ) ( "Key2" ) ( "BBB" );
// vector<A>::iterator it = find_if( vec.begin(), vec.end(), boost::bind( &map<string, string>::count, mp, boost::bind( &A::getKey, _1 ) )) != 0);
vector<A>::iterator it;
for( it = vec.begin(); it != vec.end(); ++it )
{
if( mp.count( it->getKey() ) )
{
break;
}
}
cout << ( it != vec.end() ? "found" : "not found" ) << endl;
return 0;
}
提前致谢
答案 0 :(得分:1)
你的解决方案很接近,只有一个右括号太多了。将每个括号放在换行符上,每个级别都有缩进,强调了无效的括号:
vector<A>::iterator it = find_if
(
vec.begin(), vec.end(), boost::bind
(
&map<string, string>::count, &mp, boost::bind
(
&A::getKey, _1
)
)
) // one too many
!= 0);
在最简单的形式中,该行变为iterator = find_if(...) != 0)
,这将导致编译器失败:
operator!=(iterator, int)
。 )
中的!= 0)
令牌。使用正确的括号,!= 0
使用boost::bind
提供的运算符重载。该行看起来像:
vector<A>::iterator it = find_if(vec.begin(), vec.end(),
boost::bind(&map<string, string>::count, &mp,
boost::bind(&A::getKey, _1)) != 0);
但是,请考虑这种简单操作的可读性。如果一个简单的for
循环不是通用的并且可以重用,那么考虑将它隐藏在一个便利函数中:
template <typename InputIterator,
typename C,
typename Fn>
InputIterator find_if_contains(
InputIterator first,
InputIterator last,
const C& container,
Fn fn)
{
while (first != last)
{
if (0 != container.count(fn(*first))) return first;
++first;
}
return last;
}
...
vector<A>::iterator it = find_if_contains(
vec.begin(), vec.end(),
mp, boost::bind(&A::getKey, _1)
);
否则,自定义谓词类型可以增强可读性,同时为不同类型的重用提供一些额外的灵活性。例如,请考虑以下谓词类型,该类型适用于各种类型的关联容器:
template <typename C,
typename Fn>
struct contains_predicate
{
contains_predicate(const C& container, Fn fn)
: container_(&container), fn_(fn)
{}
template <typename T>
bool operator()(T& t)
{
return 0 != container_->count(fn_(t));
}
const C* container_;
Fn fn_;
};
template <typename C,
typename Fn>
contains_predicate<C, Fn>
contains(const C& container, Fn fn)
{
return contains_predicate<C, Fn>(container, fn);
}
...
vector<A>::iterator it = find_if(vec.begin(), vec.end(),
contains(mp, boost::bind(&A::getKey, _1)));
答案 1 :(得分:0)
在C ++ 11中,使用lambda:
find_if(vec.begin(), vec.end(), [&](A const & a){return mp.count(a.getKey());});
但是既然你使用Boost.Assign而不是统一初始化,也许你不能这样做。我恐怕不知道如何仅使用bind
来构建这样的仿函数。