有任何方法可以使用STL在C ++中搜索项目或属性或变量
我们可以使用任何提供Searching time as less as possible
的STL容器。容器包含pair<int,int>
。我想搜索一对p(a,x)
,它应该返回p.first == Xi.first and p.second != Xi.second for all i
的所有对X
例如
让容器是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)
答案 0 :(得分: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。对这段代码进行模板化是留给读者的练习。
答案 1 :(得分: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
成员的指针。