【发布时间】:2017-06-19 18:51:39
【问题描述】:
我正在尝试将此答案:Replace N formulas to one (string interpolation) 移植到标准 c++98 实现。
C++14 版本:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, string> interpolate = { { "F"s, "a && b && c"s }, { "H"s, "p ^ 2 + w"s }, { "K"s, "H > 10 || e < 5"s }, { "J"s, "F && !K"s } };
for(const auto& i : interpolate) for_each(begin(interpolate), end(interpolate), [&](auto& it){ for(auto pos = it.second.find(i.first); pos != string::npos; pos = it.second.find(i.first, pos)) it.second.replace(pos, i.first.size(), '(' + i.second + ')'); });
for(const auto& i : interpolate) cout << i.first << " : " << i.second << endl;
}
C++98:制作地图:
std::map<std::string, std::string> interpolate_map;
interpolate_map.insert(std::make_pair("F", "a && b && c" ));
interpolate_map.insert(std::make_pair("H", "p ^ 2 + w" ));
interpolate_map.insert(std::make_pair("K", "H > 10 || e < 5" ));
interpolate_map.insert(std::make_pair("J", "F && !K" ));
for (const std::pair<const std::string, std::string> & i : interpolate_map)
/* ??? */
我不清楚如何进行。
【问题讨论】:
-
将 lambda 转换为仿函数。
-
我之前发布了一个map_init 助手。即使是 C++98 也可以通过合理剂量的辅助代码变得可读。