C++ 什么是正确的C++;将对象映射到函数的方法?
我的意思是,我正在制作一个程序,通过控制台从用户那里获取参数(他希望一次输入多少),例如C++ 什么是正确的C++;将对象映射到函数的方法?,c++,C++,我的意思是,我正在制作一个程序,通过控制台从用户那里获取参数(他希望一次输入多少),例如 -p /users/me/myFolder/myHtmlFile.html -d /users/me/myOtherFolder -n myHmtlFileStyles -r 将设置参数-p、-d和-n,然后运行程序(因为-r就是这样做的)。我已经编写了一个函数,它遍历输入字符串中由空格包围的每个子字符串。所以我怀疑n00b的设计模式会是 if (this_substring == "-p") {
-p /users/me/myFolder/myHtmlFile.html -d /users/me/myOtherFolder -n myHmtlFileStyles -r
将设置参数-p
、-d
和-n
,然后运行程序(因为-r
就是这样做的)。我已经编写了一个函数,它遍历输入字符串中由空格包围的每个子字符串。所以我怀疑n00b的设计模式会是
if (this_substring == "-p")
{
// ... run some procedure
}
else if (this_substring == "-d")
{
// ... run some procedure
}
else if (this_substring == "-n")
{
// ... run some procedure
}
else if (this_substring == "-r")
{
// ... run some procedure
}
else
{
// ... trigger not recognized; throw an error
}
std::map<std::string, function> triggerMap = {{"-p", function1()}, {"-d", function2()}, "-n", function3()}, {"-r", function4()}};
但我相信有一种更优雅、更恰当的方法。例如,是否有一种将string
s映射到函数的方法?是否存在类似的情况
if (this_substring == "-p")
{
// ... run some procedure
}
else if (this_substring == "-d")
{
// ... run some procedure
}
else if (this_substring == "-n")
{
// ... run some procedure
}
else if (this_substring == "-r")
{
// ... run some procedure
}
else
{
// ... trigger not recognized; throw an error
}
std::map<std::string, function> triggerMap = {{"-p", function1()}, {"-d", function2()}, "-n", function3()}, {"-r", function4()}};
std::map triggerMap={{“-p”,function1()},{“-d”,function2()},“-n”,function3()},{“-r”,function4()};
这取决于您遵循的标准。我强烈建议使用(例如,在最近的4.9编译器中,使用
-std=c++11
)。然后使用和
顺便说一句,您可以使用(如果在Linux上的话)工具。使用switch和一系列案例。识别标志(-r,-n等),提取字符并将其用作大小写标签。不是很优雅,也许是匿名的lambda闭包,但是更一般的C++。 可以从字符串到函数对象构建一个<代码>:ST::unOrdEdjPad <代码>,用lambda初始化函数对象,并根据它的密钥调用它:
std::unordered_map<std::string, std::function<void()>> fns {
{
"-p",
[]() {
// do stuff
}
},
{
"-d",
[]() {
// do something else
}
}
};
fns[param]();
std::无序映射fns{
{
“-p”,
[]() {
//做事
}
},
{
“-d”,
[]() {
//做点别的
}
}
};
fns[param]();
当然,您可以使用函数指针。
但是我建议您只使用getopt
见:
就你而言:
while ((c = getopt (argc, argv, "p:d:n:r:")) != -1)
{
switch (c)
{
case 'p':
function(optarg);
break;
case 'd':
function(optarg);
break;
case 'n':
function(optarg);
break;
case 'r':
function(optarg);
break;
}
}
您选择无序映射而不是映射的原因是什么?@stijn因为我们在这里似乎不需要排序,所以键值查找的惯用解决方案是一个哈希表,它
无序映射
是。