gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:06:25 29 4
gpt4 key购买 nike

我正在尝试移植这个答案: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:制作 map :

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

关于c++ - 从 c++14 到 c++98 的端口字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44637892/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com