在将其标记为重复之前,我已经here https://stackoverflow.com/questions/1098175/a-stdmap-that-keep-track-of-the-order-of-insertion, here https://stackoverflow.com/questions/31942783/need-stl-set-in-insertion-order, and 这里是第一个的副本 https://stackoverflow.com/questions/6278580/stl-container-that-preserves-order-of-insertion-but-allows-no-duplicates.
我知道boost::multi_index
,并使用我缺乏的环境,并且std::unordered_set
并不一定要以确定的插入顺序存储元素。
我发现使用两个容器的概念,比如说一个额外的std::vector
粗鲁无礼。
What I 会爱是一个涉及比较器的解决方案,我可以在std::set
的模板参数(澄清一下,这可能是一个简单的函子结构,包含一个bool operator()()
重载、常规函数或 lambda)。是否可以?
Addenda
-
初始化必须通过 std:: 容器的开始迭代器/结束迭代器构造函数进行,如本代码片段所示。
std::string str; cin >> str;
std::set<char>(str.begin(), str.end());
此外,另一个有趣的用例是创建一个哑散列包装函子,允许将插入顺序推入std::unordered_set
的模板参数。
您不能直接将 lambda 表达式作为集合的模板参数,因为 lambda 表达式是一个值,而集合的模板参数是一个类型。问题的明显修正,是否使用 lambda 和decltype
可以工作,导致一个有趣的问题,即 lambda 表达式表示一个uniquetype (“闭包类型”),因此您永远不能创建同一闭包类型的两个单独的 lambda 表达式。*
然而,从更抽象的意义上讲,您可以使用模板参数推导在本地上下文中实现您想要的目标,例如:
template <typename F>
int f(int* first, int* last, F comp)
{
std::set<int, F> s(comp);
while (first != last) s.insert(*first++);
...
}
现在你可以打电话f
以 lambda 表达式作为参数,因此有效地“使用 lambda 作为集合的比较器”。或者,对于一个更简单的示例,您可以为 lambda 指定一个命名变量(将所有模板推导放入一个auto
:
auto comp = [](...) { ... };
std::set<int, decltype(comp)> s(comp);
*) There is a proposal to allow lambdas in unevaluated contexts to address this point, but its outlook is uncertain. It has interesting side effects like making closure types affect name mangling.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)