简体   繁体   中英

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

Suppose I have

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

And I want to create

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

Is there a library function to do this without creating my own union/intersection function?

You can use the lambda trick to initialize a const variable:

// 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
}();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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