我想做这样的事情:
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
我该怎么做?
最佳答案
您可以使用 <functional>
中的预制仿函数:
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;
}
每一个都是一个带有 operator()
的类它接受两个参数并返回对这两个参数进行数学运算的结果。例如,std::plus<int>()(3, 4)
与3 + 4
基本相同.每个都存储为签名的函数包装对象 int(int, int)
然后根据需要调用这两个号码。
关于c++ - 是否可以将运算符用作映射中的映射值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13390296/