簡體   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