2014-10-08 57 views
-5

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

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) 
+2

以'multimap'或'unordered_multimap';使用'equal_range'来找到给定键的范围,然后遍历该范围。 – 2014-10-08 08:20:07

回答

0

沿东西线的

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。对代码进行模板化是留给读者的一个练习。

0

略多于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的成员的指向成员的模板参数来扩展此项。