在声明中合并两个常量"std::set"(不是在运行时)

Merge two constant `std::set`s in declaration (not in run-time)

本文关键字:quot std set 运行时 常量 声明 合并 两个      更新时间:2023-10-16

我试图优雅地声明一个常量std::set对象,它将是另外两个常量std::set对象的合并。

#include <set>
const std::set<int> set_one = { 1,2,3 };
const std::set<int> set_two = { 11,15 };
const std::set<int> set_all = { 1,2,3,11,15 }; // this is not very elegant, duplication

以这种方式声明set_all对象并不太优雅,因为它复制了前两行中的信息。有没有办法在声明set_all时使用set_oneset_two常量?

类似这样的东西:

const std::set<int> set_all = set_one + set_two; // this does not compile, of course!
  1. 所有对象都是严格的常量
  2. 两个源集中没有重叠的值,因此唯一性不会成为问题
  3. 我知道如何在运行时合并集合,这不是我想要的
  4. 我真的尽量避免使用这样的宏:
#include <set>
#define SET_ONE 1, 2, 3
#define SET_TWO 11, 15
const std::set<int> set_one = { SET_ONE };
const std::set<int> set_two = { SET_TWO };
const std::set<int> set_all = { SET_ONE, SET_TWO };

您可以将它们打包到lambda中并立即调用它(即IIFE(。

const std::set<int> set_all = [&set_one, &set_two]() {
std::set<int> set{ set_one.cbegin(),set_one.cend() };
set.insert(set_two.cbegin(), set_two.cend());
return set;
}(); // ---> call the lambda!

然而,如果您在全局范围中有集合(如前面提到的@Kevin(,则应该使用lambda,它将这两个集合作为参数

#include <set>
using Set = std::set<int>;    // type alias
const Set set_one = { 1,2,3 };
const Set set_two = { 11,15 };
const Set set_all = [](const Set& setOne, const Set& setTwo)
{
Set set{ setOne.cbegin(), setOne.cend() };
set.insert(setTwo.cbegin(), setTwo.cend());
return set;
}(set_one, set_two); // ---> call the lambda with those two sets!

或简称

const std::set<int> set_all = []()
{
std::set<int> set{ set_one.cbegin(),set_one.cend() };
set.insert(set_two.cbegin(), set_two.cend());
return set;
}(); // ---> call the lambda!

我知道如何在运行时合并集合,这不是我想要的对于

,不能在编译时创建std::set,因为它使用动态分配。因此,一切都发生在运行时。即使是上述λ。