【问题标题】:Search variable/item/attribute using STL in c++?在 C++ 中使用 STL 搜索变量/项目/属性?
【发布时间】:2014-12-02 19:50:53
【问题描述】:

有任何方法可以使用 STL 在 C++ 中搜索项目、属性或变量。
我们可以使用任何提供 Searching time as less as possible 的 STL 容器。容器包含 pair<int,int> 。我想搜索一对p(a,x),它应该返回所有对X,其p.first == Xi.first and p.second != Xi.second for all i
例如
让容器是 unordered_set 。

  unordered_set< pair<int , int > > myset =
  {{1,2},{1,5},{1,6},{2,4},{3,5},{4,6},{6,7},{6,8}};
  if i search for p(1,5) then it should return pair(1,2),(1,6)
  if i search for p(2,4) or (3,5),(6,7) then it should return NULL i.e. nothing
  if i search for p(6,7) then it should return pair(6,8)

【问题讨论】:

  • 参加multimapunordered_multimap;使用equal_range 查找具有给定键的范围,然后遍历该范围。

标签: c++ search stl stl-algorithm


【解决方案1】:

类似的东西

std::vector<std::pair<int, int>> 
  find_nonmatching_values(const std::unordered_multimap<int, int> & thing,
                          int key, int value) {
    std::vector<std::pair<int, int>> ret;
    auto range = thing.equal_range(key);
    std::copy_if(range.first, range.second, std::back_inserter(ret),
                 [value](const std::pair<const int, int> &p) 
                 { return p.second != value; });
    return ret;
}

Demo。将此代码模板化留给读者作为练习。

【讨论】:

    【解决方案2】:

    比 T.C.s 版本稍微通用:

    #include <type_traits>
    #include <iterator>
    
    template <typename T, typename InputIterator, typename OutputIterator, typename Comparator>
    void find_mismatches(InputIterator first, InputIterator last,
                         T const& val, OutputIterator out, Comparator comp)
    {
        for (; first != last; ++first)
        {
            auto&& f = *first;
            if (!comp(f.second, val))
                *out++ = f;
        }
    }
    
    template <typename AssociativeCont, typename OutputIterator, typename Comparator>
    void find_mismatches(AssociativeCont&& rng, typename std::remove_reference<AssociativeCont>::type::value_type const& val, OutputIterator out, Comparator comp)
    {
        auto range = rng.equal_range(val.first);
        find_mismatches(range.first, range.second, val.second, out, comp);
    }
    
    template <typename AssociativeCont, typename OutputIterator>
    void find_mismatches(AssociativeCont&& rng, typename std::remove_reference<AssociativeCont>::type::value_type const& val, OutputIterator out)
    {
        auto range = rng.equal_range(val.first);
        find_mismatches(range.first, range.second, val.second, out, std::equal_to<decltype(val.second)>());
    }
    

    Demo。请注意,您仍然可以使用模板参数来扩展它,该参数是指向value_type 成员的成员指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-18
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      相关资源
      最近更新 更多