在声明中合并两个常量"std::set"(不是在运行时)
Merge two constant `std::set`s in declaration (not in run-time)
我试图优雅地声明一个常量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_one
和set_two
常量?
类似这样的东西:
const std::set<int> set_all = set_one + set_two; // this does not compile, of course!
- 所有对象都是严格的常量
- 两个源集中没有重叠的值,因此唯一性不会成为问题
- 我知道如何在运行时合并集合,这不是我想要的
- 我真的尽量避免使用这样的宏:
#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
,因为它使用动态分配。因此,一切都发生在运行时。即使是上述λ。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- 如何检测我何时向可变参数函数传递"std::string"而不是"c_str()"