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

标签 c++ dictionary 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

我该怎么做?

最佳答案

您可以使用 <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/

相关文章:

javascript - 如何查找在 Map JavaScript 中用作键的类实例?

c++ - GoingNative2012看到的operator""是什么

c++ - GLSL 着色器中的链接器错误?

c++ - CUDA:对传递给 GPU 的数组的每个第 n 个点进行分组

python - 如何将具有一列的 csv 文件转换为 Python 中的字典?

c++ - C++ 中链表的重载运算符 +=

c++ - 如何定义静态运算符<<?

c++ - 成员变量在 Tick 上失去值(value)(c++)

c++ - 在 x64 上获取真正的 C++ 异常

python - 访问嵌套字典中的值