[英]const_iterator, find_if and bind2nd: no match for call to error
我嘗試使用find_if通過鍵的值在映射中查找鍵。 但是我不能編譯代碼:
struct IsCurrency : binary_function<pair<const Bill::CodeCurrency, string>, string, bool> {
bool isCurrency(const pair<const Bill::CodeCurrency, string>& element, const string& expected) const {
return element.second == expected;
}
};
string currency = "RUB";
map<Bill::CodeCurrency, string>::const_iterator my_currency = find_if(Bill::currency_code_map().begin(), Bill::currency_code_map().end(), bind2nd(IsCurrency(), currency)); /// <--- ERROR IS HERE
Bill::CodeCurrency
是一個枚舉。
錯誤:
/usr/include/c++/4.7/bits/stl_algo.h:4490:41: required from ‘_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_const_iterator<std::pair<const Bill::CodeCurrency, std::basic_string<char> > >; _Predicate = std::binder2nd<IsCurrency>]’
../src/money_acceptor/itl_bill_acceptor.cpp:182:121: required from here
/usr/include/c++/4.7/backward/binders.h:155:29: error: no match for call to ‘(const IsCurrency) (const first_argument_type&, const second_argument_type&)’
您能幫我確定這是什么錯誤嗎?
用bool isCurrency(...)
bool operator () (...)
替換bool isCurrency(...)
bool operator () (...)
以使您的結構可調用。
如我的評論中所述,實際的問題是,提供給find_if
的謂詞需要具有operator()
,而不是名稱類似於類名的某些函數。
C ++ 03版本:
#include <map>
#include <functional>
#include <string>
#include <algorithm>
namespace Bill
{
enum CodeCurrency
{
A, B, C
};
typedef std::map<CodeCurrency, std::string> currency_code_map_t;
currency_code_map_t const& currency_code_map()
{
static currency_code_map_t m;
return m;
}
}
struct IsCurrency
: std::binary_function< Bill::currency_code_map_t::value_type, std::string,
bool >
{
bool operator()(Bill::currency_code_map_t::value_type const& element,
std::string const& expected) const
{
return element.second == expected;
}
};
int main()
{
std::string currency = "RUB";
Bill::currency_code_map_t::const_iterator my_currency =
std::find_if( Bill::currency_code_map().begin(),
Bill::currency_code_map().end(),
bind2nd(IsCurrency(), currency) );
}
C ++ 11版本:
#include <map>
#include <functional>
#include <string>
#include <algorithm>
namespace Bill
{
enum CodeCurrency
{
A, B, C
};
typedef std::map<CodeCurrency, std::string> currency_code_map_t;
currency_code_map_t const& currency_code_map()
{
static currency_code_map_t m;
return m;
}
}
int main()
{
std::string currency = "RUB";
auto check = [¤cy](Bill::currency_code_map_t::value_type const& element)
{ return element.second == currency; };
auto my_currency =
std::find_if( Bill::currency_code_map().cbegin(),
Bill::currency_code_map().cend(),
check );
}
請注意,此算法為O(N)。 如果您需要經常查找元素(可能是O(logN)),則可能要考慮使用boost::bimap
類的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.