【发布时间】:2018-12-21 23:37:54
【问题描述】:
由于基于范围的循环很流行,所以我试图弄清楚如何以一种有效的方式编写以下代码,它使用基于范围的循环。
但请随意重构代码和/或建议另一种构造,这可能被认为是处理 std::map 的连续键的更好方法
C++11 兼容的答案是首选,但只是为了知识,请随意推荐任何来自 boost 或 C++14 的东西
void mapRangeLoop()
{
std::map<std::string, std::vector<int>> infoMap;
// **** Piece of Code to be improved BEGIN *********
std::for_each(infoMap.rbegin(), infoMap.rend(), [&infoMap](auto& it) {
auto prev = std::prev(infoMap.find(it.first)); // <---I would like to avoid use of find() to get the iterator
if (prev != infoMap.end() && isSubString(prev->first, it.first))
for (auto& p : prev->second)
processVectors(p, it.second);
});
// **** Piece of Code to be improved END *********
// Same thing could be achieved through traditional for loop like this
for (auto it = infoMap.rbegin(); it != infoMap.rend(); ++it)
{
auto prev = std::next(it);
if (prev != infoMap.rend() && isSubString(prev->first, it->first))
for (auto& p : prev->second)
processVectors(p, it->second);
}
}
//Just for completeness
bool isSubString(const std::string& s1, const std::string& s2)
{
// returns true or false based on some logic
}
void processVectors(const int i, std::vector<int>& vec)
{
// Some logic to modify vec based on value of i
}
【问题讨论】:
-
std::map上的基于范围的循环将为您提供std::pair<const Key,Value>。 -
看来你想要
std::adjacent_find。