从 c++14 到 c++98 的端口字符串插值

port string interpolation from c++14 to c++98

我正在尝试移植这个答案: 到标准的 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)
/* ??? */

我不清楚如何进行。

里面有很多东西,写它的人真的很了解他的东西。

您正在查看的代码使用 样式的 for 循环、for_each 循环和传统的 for 循环来有效地做三件事:

  1. 遍历所有可以插入的键
  2. 遍历所有值字符串进行插值
  3. 遍历整个字符串以插入所有键

中,您最好的选择可能只是三重嵌套 for 循环:

for(map<string, string>::iterator i = interpolate.begin(); i != interpolate.end(); ++i) {
    for(map<string, string>::iterator it = interpolate.begin(); it != interpolate.end(); ++it) {
        for(string::size_type 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 + ')');
        }
    }
}

Live Example