【问题标题】:how to create an adaptor that will return map values based on filtered key using a predicate for key如何创建一个适配器,该适配器将使用键的谓词基于过滤的键返回映射值
【发布时间】:2014-04-29 06:16:12
【问题描述】:

如何创建一个适配器,该适配器将使用键的谓词根据过滤后的键返回映射值?

举个例子:

std::map<int,int> map_obj; 
const int match_value = 0xFF00;
for(auto& i : map_obj | filtered_key_map_values([match_value](key_type& x){ return (x & match_value) > 0; } | indirected )
{
    std::copy<typeof(i)>(std::cout," ,"); 
}

【问题讨论】:

  • 下一次,您需要将其标记为boost-range,或在您的问题中明确标记。

标签: c++ boost map boost-range


【解决方案1】:

这是我推荐的一个版本Live On Coliru

#define BOOST_RESULT_OF_USE_DECLTYPE
#include <boost/range/adaptors.hpp>

using namespace boost::adaptors;
#include <iostream>

int main()
{
    std::map<int, std::string> const map_obj {
        { 0x0001, "one"   },
        { 0x0002, "two"   },
        { 0x0003, "three" },
        { 0x0404, "four"  },
        { 0x0005, "five"  },
    }; 

    const int match_value = 0xFF00;
    for(auto& v : map_obj
         | filtered([=](std::pair<const int, std::string> const& p)->bool { return (p.first & match_value) != 0; })
         | map_values)
    {
        std::cout << v << "\n";
    }
}

【讨论】:

  • 谢谢。是的,这听起来很有趣。我想我必须更多地研究 lambda。
  • @Shaikat 如果您想知道,您也可以使用主流编译器 in C++11 mode(MSVC、gcc、clang)编译它,但它稍微冗长 :)
  • 感谢您解释过滤器的使用。大多数示例使用具有不依赖于外部变量的函数的向量。
  • 干杯。感谢您的反馈
  • @Shaikat 注意到您的编辑。而且我将其修复为更正确/更有效(无需在过滤期间复制所有内容)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
相关资源
最近更新 更多