यदि आप सी ++ के लिए नए हैं, तो अपनी स्थापना में नए पुस्तकालय (टेम्पलेट या अन्यथा) जोड़ना सीखने की वक्र को बढ़ाएगा। यह कुछ ऐसा है जो आप अंतर्निहित सुविधाओं के साथ आसानी से, सुंदर और कुशलता से कर सकते हैं।
समान उत्तरों के विपरीत, इस कोड इनपुट से अधिक केवल एक पास बनाता है और बड़े शब्दकोशों के साथ अच्छी तरह से अनुरूप:
// header
#include <map>
#include <sstream>
typedef std::map< std::string, std::string > subst_map;
// implementation
using namespace std;
string do_substitutions(string const &in, subst_map const &subst) {
ostringstream out;
size_t pos = 0;
for (;;) {
size_t subst_pos = in.find("{{", pos);
size_t end_pos = in.find("}}", subst_pos);
if (end_pos == string::npos) break;
out.write(&* in.begin() + pos, subst_pos - pos);
subst_pos += strlen("{{");
subst_map::const_iterator subst_it
= subst.find(in.substr(subst_pos, end_pos - subst_pos));
if (subst_it == subst.end()) throw runtime_error("undefined substitution");
out << subst_it->second;
pos = end_pos + strlen("}}");
}
out << in.substr(pos, string::npos);
return out.str();
}
// usage
pair< string, string > substitutions_init[] = {
make_pair("firstname", "homer"),
make_pair("lastname", "simpson")
};
subst_map substitutions
(substitutions_init, substitutions_init + sizeof(substitutions_init)/sizeof(*substitutions_init));
int main() {
cerr << do_substitutions("Mr. {{lastname}}, {{firstname}} esquire", substitutions) << endl;
}
'टेम्पलेट्स' टैग यहां उचित नहीं है। एक टेम्पलेट स्ट्रिंग के भीतर तारों को प्रतिस्थापित करना सी ++ संदर्भ में टेम्पलेट के सामान्य अर्थ के समान नहीं है। –
'वास्तविक एक' से, आपका मतलब स्ट्रिंग टेम्पलेट के दायरे में परिभाषित 'नाम' नामक एक चर है? –
सवाल क्या है? –