gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:37:14 26 4
gpt4 key购买 nike

我正在尝试优雅地声明一个常量 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!

但是,如果您有 the global scope(like @Kevin mentioned) 中的集合,您应该使用将两个集合作为参数的 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!

I know how to merge sets in runtime, this is not what I am lookingfor.

,您不能创建std::set在编译时使用 dynamic allocation .因此,一切都发生在运行时。即使是上面的 lambda。

关于c++ - 在声明中合并两个常量 `std::set`(不是在运行时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62800808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com