Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 是否可以将运算符用作映射中的映射值?_C++_Map_Operator Keyword - Fatal编程技术网

C++ 是否可以将运算符用作映射中的映射值?

C++ 是否可以将运算符用作映射中的映射值?,c++,map,operator-keyword,C++,Map,Operator Keyword,我想这样做: int a = 9, b = 3; map<char,operator> m; m['+'] = +; m['-'] = -; m['*'] = *; m['/'] = /; for(map<char,operator>::iterator it = m.begin(); it != m.end(); ++it) { cout << func(a,b,it -> second) << endl; } 12 6 27 3

我想这样做:

int a = 9, b = 3;
map<char,operator> m;
m['+'] = +;
m['-'] = -;
m['*'] = *;
m['/'] = /;
for(map<char,operator>::iterator it = m.begin(); it != m.end(); ++it) {
    cout << func(a,b,it -> second) << endl;
}
12
6
27
3

如何执行此操作?

您可以在以下位置使用预制函子:


每个类都有一个运算符,该运算符接受两个参数并返回对这两个参数的数学运算结果。例如,std::plus3,4与3+4基本相同。每个函数都存储为签名int,int的函数包装器对象,然后根据需要使用两个数字进行调用。

您可以在以下位置使用预制函子:


每个类都有一个运算符,该运算符接受两个参数并返回对这两个参数的数学运算结果。例如,std::plus3,4与3+4基本相同。每个都存储为签名int,int的函数包装器对象,然后根据需要使用两个数字进行调用。

您不能这样做!没有类型运算符。不能将运算符作为模板参数。@Jarryd,我刚刚注意到了这一点。现在应该修好了。是的,这样更好。你们在我写那个评论的时候编辑了它。@hinafu,看看boost::function。至于模板问题,std::map。放一个空间就足以解决这个问题。boost::function的工作方式与std::function的工作方式大致相同。@hinafu:如果您被迫在没有boost的情况下使用C++03,在这种情况下,您可以使用老式的函数指针std::map。您需要为每个操作编写自己的函数。您不能这样做!没有类型运算符。不能将运算符作为模板参数。@Jarryd,我刚刚注意到了这一点。现在应该修好了。是的,这样更好。你们在我写那个评论的时候编辑了它。@hinafu,看看boost::function。至于模板问题,std::map。放一个空间就足以解决这个问题。boost::function的工作方式与std::function的工作方式大致相同。@hinafu:如果您被迫在没有boost的情况下使用C++03,在这种情况下,您可以使用老式的函数指针std::map。您需要为每个操作编写自己的函数。
int a = 9, b = 3;
std::map<char, std::function<int(int, int)>> m;

m['+'] = std::plus<int>();
m['-'] = std::minus<int>();
m['*'] = std::multiplies<int>();
m['/'] = std::divides<int>();

for(std::map<char, std::function<int(int, int)>>::iterator it = m.begin(); it != m.end(); ++it) {
    std::cout << it->second(a, b) << std::endl;
}