繁体   English   中英

在 C++ 中创建一个值为两个集合的并集/交集的常量集的标准方法?

[英]Standard way to create a const set with the value as a union/intersection of two sets in C++?

假设我有

constexpr std::set<int> a = {1, 2, 3};
constexpr std::set<int> b = {3, 4, 5};

我想创造

constexpr std::set<int> c = union(a, b); // {1, 2, 3, 4, 5}

是否有库函数可以在不创建自己的联合/交集函数的情况下执行此操作?

您可以使用 lambda 技巧来初始化一个const变量:

// need to capture `a`, `b` if this is at block scope
const std::set<int> c = []() {
    std::set<int> result;
    std::set_union(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.end()));
    return result;  // compiler can probably NRVO this
}();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM