是否可以在地图中使用运算符作为映射值?

hin*_*afu 1 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;
}
Run Code Online (Sandbox Code Playgroud)

输出是这样的:

12
6
27
3
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

chr*_*ris 6

您可以在<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;
}
Run Code Online (Sandbox Code Playgroud)

每个都是一个带有operator()两个参数的类,并返回这两个参数的数学运算结果.例如,std::plus<int>()(3, 4)基本相同3 + 4.每个都存储为签名的函数包装器对象,int(int, int)然后根据需要使用两个数字进行调用.

  • @hinafu:如果你被迫在没有Boost的情况下使用C++ 03,你可以在这种情况下使用旧式函数指针`std :: map <char,int(*)(int,int)>`.您需要为每个操作编写自己的函数. (2认同)