std :: map with lambda comparator

时间:2013-10-19 01:33:39

标签: c++ c++11 stl lambda

我的下面的代码给了我编译错误,我不明白我在做什么错。有人可以帮忙吗?

基本上我所要做的就是通过引用传递一个STL地图容器来填充它。此映射容器还有一个与之关联的比较器lambda。

#include "stdafx.h"
#include <functional>
#include <map>

using namespace std;

typedef struct _tagAddressBook
{
  string strFirstName;
  string strLastName;
  long nZipCode;
} AddressBook;

void foo(map<string, AddressBook, function<bool(const string&, const string&)>> &myAddressBook)
{
  AddressBook addressBookInstance;
  addressBookInstance.strFirstName = "Bob";
  addressBookInstance.strLastName = "Parker";
  addressBookInstance.nZipCode = 12345;

  myAddressBook.insert(std::pair<string, AddressBook>(addressBookInstance.strFirstName, addressBookInstance));
}

int _tmain(int argc, _TCHAR* argv[])
{
  auto myComparator = [] (const string &strLeft, const string &strRight) { return(strLeft.compare(strRight) <= 0 ? true : false); };
  map<string, AddressBook, decltype(myComparator)> myAddressBook(myComparator);

  foo(myAddressBook);

    return 0;
}

我在VS2012上得到以下编译错误

错误1错误C2664:'foo':无法从'std :: map&lt; _Kty,_Ty,_Pr&gt;'转换参数1到'std :: map&lt; _Kty,_Ty,_Pr&gt; &安培;” d:\ my projects \ mapwithlambdacomparator \ mapwithlambdacomparator \ mapwithlambdacomparator.cpp 32

2   IntelliSense: a reference of type "std::map<std::string, AddressBook, std::function<bool (const std::string &, const std::string &)>, std::allocator<std::pair<const std::string, AddressBook>>> &" (not const-qualified) cannot be initialized with a value of type "std::map<std::string, AddressBook, lambda []bool (const std::string &strLeft, const std::string &strRight)->bool, std::allocator<std::pair<const std::string, AddressBook>>>" d:\My Projects\MapWithLambdaComparator\MapWithLambdaComparator\MapWithLambdaComparator.cpp  32

2 个答案:

答案 0 :(得分:1)

Lambda函数与std::function无关。实际上,每个都是它自己的类类型。如果你想做你看来做的事情,可以通过foo模板进行,然后扣除它。

template <typename Cmp>
void foo(map<std::string, AddressBook, Cmp> &myAddressBook)
{
    AddressBook addressBookInstance;
    addressBookInstance.strFirstName = "Bob";
    addressBookInstance.strLastName = "Parker";
    addressBookInstance.nZipCode = 12345;

    myAddressBook.insert(std::pair<string, AddressBook>(addressBookInstance.strFirstName, addressBookInstance));
}

这适用于我的工具链,“Apple LLVM 5.0版(clang-500.2.75)(基于LLVM 3.3svn)”。我认为没有理由不能使用你的工具链。

答案 1 :(得分:1)

请别名:

using AdressBookMap = map<string, AddressBook, function<bool(const string&, const string&)>>;

然后使用它:

void foo(AddressBookMap& myAddressBook)
{
    // ...
}

int main(int argc, char* argv[])
{
    auto myComparator = [] (...) { ... };
    AddressBookMap myAddressBook(myComparator);

    foo(myAddressBook);

    return 0;
}

正如Whoz所说,lambdas不是std::function;后者可以从前者隐式构造,但它们不具有相同的类型。这意味着由{1}参数化的std::map与由另一个参数化的std::map完全无关。