簡體   English   中英

隱式轉換為比較 function object(仿函數)用於 std::sort 但不是 std::map?

[英]Implicit conversion to comparison function object (functor) for std::sort but not std::map?

我一直在使用帶有 function 的std::sort作為比較 function。 function 被隱式轉換為仿函數(通過 GCC)。 我在聲明std::map類型時嘗試了相同的方法,但這失敗了。

使用g++ g++ -Wall -Wextra -std=gnu++14 -pedantic

#include <map>
#include <algorithm>
#include <vector>

struct S { int i; };
struct Payload { bool b; };

bool compare(const S* const& lhs, const S* const& rhs)
{
    return lhs->i < rhs->i;
}

using MyMap = std::map<const S*, Payload, compare>;

static void foo([[maybe_unused]] const MyMap&) {}

int main()
{
    std::vector<const S*> vs;
    std::sort(vs.begin(), vs.end(), compare); // OK

    MyMap m;
    foo(m);
}

這是 output:

main.cpp:13:50: error: type/value mismatch at argument 3 in template parameter list for 'template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map'
   13 | using MyMap = std::map<const S*, Payload, compare>;
      |                                                  ^
main.cpp:13:50: note:   expected a type, got 'compare'

有沒有一種方法可以將函子傳遞給map聲明,而無需手動定義函子 class (因為可以使用std::sort )?

您似乎混淆了類型和值。 std::sort的第三個參數是一個值, std::map的第三個參數是一個類型。

using MyMap = std::map<const S*, Payload, bool (*)(const S* const&, const S* const&)>;

完全合法。

然后你可以寫

MyMap my_map(compare);

PS在您的排序示例中沒有隱式轉換為仿函數。 作為模板 function 可以使用任何合法的 function 調用運算符調用排序。 這包括函子和 function 指針(除其他外)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM