gpt4 book ai didi

c++ - 使用自定义比较器返回 std::set

转载 作者:行者123 更新时间:2023-12-03 06:52:25 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来返回 std::set使用自定义比较器(根据来自 this answer 的建议),如下所示:

#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 )它会产生以下错误:

Error C2783 'void std::swap(_Ty &,_Ty &) noexcept()': could not deduce template argument for '_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;
}
这适用于两个编译器。

关于c++ - 使用自定义比较器返回 std::set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63878001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com