返回映射中符合条件的一组键
首先我将给出一个具体案例,然后我想看看它是否可以应用于一般问题。
说我有地图。 我想让所有的钥匙都满足一定的标准。 例如,所有包含“COL”的键。 我天真的实现将是
template<typename T>
void Filter (map<string, T> & m, std:set<string> & result, const std::string& condition)
{
for(map<string,string> iter=m.begin();iter!m.end();iter++)
{
std::string key=iter->first;
size_t found=key.find(condition);
if (found!=string::npos)
result.insert(key);
}
}
什么是实现这个的好方法?
另外,当我想使用算法过滤地图时,实现一般问题的好方法是什么?
First I will give a specific case, and the I would like to see if it can be applied to a general problem.
Say I have map. And I want to get all the keys meeting a certain criteria.
For example all keys that contain "COL". My naive implementation will be
template<typename T>
void Filter (map<string, T> & m, std:set<string> & result, const std::string& condition)
{
for(map<string,string> iter=m.begin();iter!m.end();iter++)
{
std::string key=iter->first;
size_t found=key.find(condition);
if (found!=string::npos)
result.insert(key);
}
}
what is the good way to implement this?
Also, what is a good way to implement general problem when I want to filter map using algos?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这看起来像是
remove_copy_if
的候选者。 我使用boost
写了一些东西,它看起来可能不仅仅是恶心,但提供了算法的概括。我可能更喜欢手动循环。 C++1x 会让 lambda 表达式看起来更好。
That looks like a candidate for
remove_copy_if
. I've written something usingboost
that probably looks more than disgusting, but provides a generalization of your algorithm.I would probably prefer the manual loop. C++1x will make look that really much better with lambda expressions.
我认为你的解决方案相当好:它很清楚,除非你可以根据条件“猜测”哈希值,否则我认为你的性能不会更高。 但是,您可以更改函数以使其更加通用:
然后可以使用函子作为谓词来编写示例:
对过滤器的调用将如下所示:
I think your solution is rather good: it is clear, and except if you can "guess" hash values based on the condition, I don't think you could be much more performant. However, you could change your function to make it more generic:
Your example can then be writen using a functor as predicate:
The call to filter will then look like this:
看看下面。 不过,这是未经测试的东西,因此您可能需要修复它。
}
看一下
std::transform
。Take a look below. This is untested stuff though so you may need to fix it.
}
Take a look at
std::transform
.首先,一些非常小的建议:
在更一般地处理此类任务时,我实际上更喜欢像您一样的显式循环。 std::map 无论如何都没有提供更有效的键迭代机制。
替代方案包括
std::for_each
加上boost::bind
,或boost::lambda
。First, some very minor suggestions:
++iter
, which saves you one copy of the iteratorOn the more general handling of this sort of tasks, I tend to actually prefer explicit loops like you did. std::map does not provide a more efficient keys iteration mechanism anyway.
Alternatives would include
std::for_each
coupled withboost::bind
, orboost::lambda
.您也可以这样做:
在调用代码中:
You can also do it like this:
In the calling code: