【发布时间】:2020-10-14 12:48:36
【问题描述】:
我想减少重复的代码。下面是一段sn-p代码
void f1(string arg)
{
std::map <string,string> topicAndClientIdMap;
for(auto topicAndClientId : topicAndClientIdMap)
{
if(topicAndClientId.second == arg1)
{
//inset in other map
}
}
}
void f2(string arg)
{
std::map <string,string> topicAndClientIdMap;
for(auto topicAndClientId : topicAndClientIdMap)
{
if(topicAndClientId.first.contains(arg1))
{
//insert in other map
}
}
}
我想为f1 和f2 创建一个通用函数,我也可以在其中传递条件。
【问题讨论】:
-
您正在寻找lambda expressions,可能嵌入在std::for_each中。
-
您确实在寻找算法库中的std::transform 或此处的变体。
-
topicAndClientIdMap是两个函数中的局部变量。你真正想做什么? -
您的代码无法编译。请创建一个minimal reproducible example,以便清楚您要重构的是什么。