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

北城以北 提交于 2019-12-04 02:38:51

问题


I'm trying to port this answer: Replace N formulas to one (string interpolation) to a standard c++98 implementation.

C++14 version:

#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: Making the 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)
/* ??? */

It's unclear to me how to proceed.


回答1:


There's a lot of involved c++11 in that, whoever wrote it really knows his stuff.

The code that you're looking at uses a c++11 style for-loop, a for_each-loop, and a traditional for-loop to effectively do three things:

  1. Loop through all the keys that could be interpolated
  2. Loop through all the value strings to interpolate
  3. Loop through the entire string to interpolate all keys

In c++98 your best bet is likely just a triple nested 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



来源:https://stackoverflow.com/questions/44637892/port-string-interpolation-from-c14-to-c98

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!