我有几个标准的整数集,我需要能够从多个翻译单元访问它们。目标是根据代码的上下文获取这些标准集并将它们放入本地集。
例如,我的最佳解决方案是:
#include <boost/assign/list_of.hpp>
#include <set>
const std::set<int> set9 =
boost::assign::list_of(4)(10)(108);
const std::set<int> set10 =
boost::assign::list_of(3)(5)(10)(108);
const std::set<int> set11 =
boost::assign::list_of(2)(3)(5)(101);
int main(void)
{
std::set<int> my_set(set9);
my_set.insert(set11.begin(), set11.end());
return 0;
}
它们不需要是常量全局变量,事实上,我可能更喜欢函数,但如果它们是函数,那么每次我想使用多个时我都必须添加额外的行和额外的 set 变量。
它看起来像这样(比以前多了一套标准):
std::set<int> my_set(get_set9());
std::set<int> extra_line(get_set11());
my_set.insert(extra_line.begin(), extra_line.end());
std::set<int> another_extra_line(get_set12());
my_set.insert(another_extra_line.begin(), another_extra_line.end());
除非我遗漏了什么?
我更喜欢函数的原因是有额外的复杂性。在常量集中,有重复的值具有相关的含义,因此我不想每次都重复它们以防发生变化(并防止代码重复)。
在我前面的例子中,10 和 108 是相连的,应该总是一起出现。如果这些是函数,我可以让 get_set11() 和 get_set12() 调用一个通用函数(比如 get_set2() ,它只有 10 和 108)。但是,使用常量集方法,我不确定如何构建这些包含其他集合的常量集。我想到的最好的是:
#include <boost/assign/list_of.hpp>
#include <set>
#define APPLY_COMMON_SET(prev) \
prev(10)(8)
const std::set<int> set2 =
APPLY_COMMON_SET(boost::assign::list_of);
const std::set<int> set9 =
APPLY_COMMON_SET(boost::assign::list_of(4));
const std::set<int> set10 =
APPLY_COMMON_SET(boost::assign::list_of(3)(5));
const std::set<int> set11 =
boost::assign::list_of(2)(3)(5)(101);
#undef APPLY_COMMON_SET
int main(void)
{
std::set<int> my_set(set9);
my_set.insert(set11.begin(), set11.end());
return 0;
}
这行得通,但我宁愿避免预处理器宏。
这不编译,但我希望能够做这样的事情:
const std::set<int> set2 =
boost::assign::list_of(10)(108)
const std::set<int> set9 =
boost::assign::list_of(4) + set2;
const std::set<int> set10 =
boost::assign::list_of(3)(5) + set2;
有没有不用宏的方法,或者这是我唯一的选择?
最佳答案
任何特定的性能限制?你可以只实现你在最后使用的加法:
typedef std::set<int> intset;
intset onion(intset lhscp, const intset &rhs) {
lhscp.insert(rhs.begin(), rhs.end());
return lhscp;
}
const intset set10 = onion(boost::assign::list_of(2)(5), set2);
关于c++ - 由元素和其他集合组成的集合,用于在 C++ 中构造集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4211101/