在为请求选择服务的情况下,使用Boost ICL而不是for_each是否可能且合理
Is it possible and resonable to use Boost ICL instead of for_each in case of selecting a service for request?
我有一个request
结构,其中有std::vector<std::string> arguments
。我有std::map<std::string, std::vector<std::string> > services
,其中key是服务名称,value是服务响应的参数向量。不同服务的参数可能重叠(N
服务可能具有相同或部分相同的参数)。我需要找到与给定请求相对应的所有服务。我想知道使用Boost ICL而不是我用于服务选择的当前for_each是否会更好(从代码的易用性或阅读性以及请求选择速度来看,最重要的是)?
我会选择可读性最强的变体。如果性能有问题,只需将参数(集)的适用服务缓存到多映射中即可。
如果我的想法是正确的,下面显示了一些c++11/boost语法糖,它展示了我的可读性:
#include <boost/range/numeric.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
typedef std::vector<std::string> args_t;
typedef std::map<std::string, args_t> service_map;
struct applicable
{
template <typename T>
applicable(const T& args) : _args(args) { }
bool operator()(const service_map::value_type& svc) const
{
for (auto& a:_args)
if (svc.second.end() == boost::find(svc.second, a))
return false;
return true;
}
private: args_t _args;
};
int main(int argc, const char *argv[])
{
using namespace boost::adaptors;
static const service_map services {
{ "A", { "1","2","3" } },
{ "B", { "2","3","4" } },
{ "C", { "3","4","5" } },
{ "D", { "4","5","6" } }
};
const std::string label = "request: ";
for (const auto& req : std::list<args_t> { {"5"}, {"4","3"}, {"1","3"} })
{
std::cout << boost::accumulate(req, label) << std::endl;
for (auto& svc : services | filtered(applicable(req)))
std::cout << "applicable: " << svc.first << std::endl;
}
}
当然,可以应用许多优化。但你知道他们怎么说过早优化:)
输出:
request: 5
applicable: C
applicable: D
request: 43
applicable: B
applicable: C
request: 13
applicable: A
相关文章:
- C++ 中用于二维数组的 for-each 循环
- 计算 fib(n) 的次数称为 FOR EACH n
- 支持自定义 const 本机C++容器类的"for each"
- C++ for-each 语句触发"vector iterators incompatible"断言失败:this->_Getcont() == 0
- 为什么我的矢量中的项目在 C++ 中的 for-each 循环期间不会改变?
- 当循环返回"for each"项的 nullptr 时?
- 正确使用C++ 'for each'选项
- "for each"能保证使用更改数组吗?
- 基于范围的循环与 for-each 循环有何不同
- C++:从"for each"循环中的映射中删除值
- 将函数应用于std::map值,其中包含for each和lambda函数
- 正在擦除for(-each)自动循环中的项目
- g++ 4.4.7 -std=gnu++0x 应该编译"for each"结构吗?
- 将循环转移到C++03 for each
- 在 for-each 循环中使用 'auto' 时是否需要添加'const'?
- C++中的"for each"循环如何知道数组的长度
- 基本c++: for-each循环
- 如何使c++中的for each循环函数与自定义类一起工作
- 如何使用for-each循环来美化析构函数
- for-each 循环生成错误,但 for(it=begin()...在遍历 std::map 包含 unique_ptr 时不会