【问题标题】:port string interpolation from c++14 to c++98从 c++14 到 c++98 的端口字符串插值
【发布时间】: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 也可以通过合理剂量的辅助代码变得可读。

标签: c++ c++98


【解决方案1】:

其中涉及很多,写它的人真的很了解他的东西。

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

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

中,您最好的选择可能只是一个三重嵌套的for-loop:

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

【讨论】:

  • 除了现场演示(在我的编译器中)之外它可以工作,因为地图不能像那样初始化(我使用了问题中的初始化)。向梅先生致敬。
  • @AnnaK。你应该被允许初始化一个map,但是如果你的编译器很糟糕,insert 方法可以工作。
  • 我明白了:错误:在 C++98 中,'interpolate' 必须由构造函数初始化,而不是由 '{...}' 和警告:扩展初始化列表仅适用于 -std=c ++11 或 -std=gnu++11
  • @AnnaK。您似乎对初始化是正确的,我认为 gcc6.3 默认为没有标志的 C++03,结果它默认为 C++14。因此,我真的在使用 mapinitializer_list 构造函数,你们中的哪一个正确地猜测是 not 在 C++98 中可用:stackoverflow.com/q/44654713/2642059
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多