簡體   English   中英

使用自定義比較器返回 std::set

[英]Return a std::set with a custom comparator

我正在嘗試編寫一個函數來返回帶有自定義比較器的std::set (根據此答案中的建議),如下所示:

#include <iostream>
#include <set>

auto GetSet()
{
    const auto cmp = [](auto n1, auto n2) { return n1 < n2; };
    std::set<int, decltype(cmp)> mySet(cmp); // compiler error, see below
    mySet.insert(13);
    mySet.insert(31);
    return mySet;
}
int main()
{
    auto mySet = GetSet();
    for (auto i : mySet)
        std::cout << i << " ";
}

顯然這是出於演示目的,我的int更復雜

它在 GCC Coliru link中工作正常,但在 VS2019 中不起作用。 在 VS2019(使用/std:c++17 )中,它會產生以下錯誤:

錯誤 C2783 'void std::swap(_Ty &,_Ty &) noexcept()': 無法推導出 '_Enabled' C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Professional\\VC\\Tools\\ 的模板參數MSVC\\14.27.29110\\include\\utility 114

如果我將代碼更改為不使用該函數,而是具有:

int main()
{
    const auto cmp = [](auto n1, auto n2) { return n1 < n2; };
    std::set<int, decltype(cmp)> mySet(cmp);
    mySet.insert(13);
    mySet.insert(31);
    for (auto i : mySet)
        std::cout << i << " ";
}

它工作正常。 上面有什么問題嗎,還是微軟更迂腐,或者某種編譯器錯誤?

我對出了什么問題沒有答案(無論 GCC 是馬虎還是 MSVC 更迂腐),但您可以使用以下內容:

#include <set>
#include <functional>
auto GetSet()
{
    const auto cmp = [](auto n1, auto n2) { return n1 < n2; };
    std::set<int, std::function<bool(int, int)>> mySet(cmp);
    mySet.insert(13);
    mySet.insert(31);
    return mySet;
}

這適用於兩個編譯器。

暫無
暫無

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

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