c++ - 如何定义从函数指针到字符串的映射

标签 c++ stl

我试图在 C++ 中定义一个从成员函数指针到字符串的映射。但是编译器提示 operator < 没有为成员函数指针定义。有办法做到这一点吗?

示例代码:

#include <map>
#include <string>
class foo;
typedef void (foo::*fooFunc)();

class foo {
public:
  foo() {
    myMap[func]="example function";
  }
  void func() {};
  std::map<fooFunc,std::string> myMap;
};

产生的错误信息:

    In file included from C:/msys64/mingw64/include/c++/6.2.0/bits/stl_tree.h:65:0,
                 from C:/msys64/mingw64/include/c++/6.2.0/map:60,
                 from grr.cpp:1:
C:/msys64/mingw64/include/c++/6.2.0/bits/stl_function.h: In instantiation of 'constexpr bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = void (foo::*)()]':
C:/msys64/mingw64/include/c++/6.2.0/bits/stl_map.h:501:32:   required from 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = void (foo::*)(); _Tp = std::__cxx11::basic_string<char>; _Compare = std::less<void (foo::*)()>; _Alloc = std::allocator<std::pair<void (foo::* const)(), std::__cxx11::basic_string<char> > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::__cxx11::basic_string<char>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = void (foo::*)()]'
grr.cpp:9:15:   required from here
C:/msys64/mingw64/include/c++/6.2.0/bits/stl_function.h:386:20: error: invalid operands of types 'void (foo::* const)()' and 'void (foo::* const)()' to binary 'operator<'
       { return __x < __y; }
                ~~~~^~~~~

最佳答案

std::map它的键需要一个比较运算符。默认情况下,它使用 operator < .自 operator <没有为指向成员的指针 类型定义,您将收到此错误。 要修复它,您需要定义自定义比较运算符并将其作为参数提供给 std::map .或者,使用不同的容器。

来自 cppreference :

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees

如果您需要有关如何编写此类比较运算符的选项,已经有答案here .

关于c++ - 如何定义从函数指针到字符串的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49833877/

相关文章:

c++ - 查看时间戳是否在特定时间之间

c++ - 添加自定义析构函数时, move 构造函数在派生类中消失

c++ - 使用哪个排序的 STL 容器来通过特殊键进行快速插入和查找?

c++ - 尝试将 std::pair 插入 std::set

c++ - 是否可以在 multimap 中使用自定义查找功能?

c++ - 关于在 C++ 中使用 "+"的整数变量和字符串连接的非常基本的问题

c++ - 如何从txt文件中读取矩阵到模板矩阵?

c++ - 有没有办法限制 STL::map 容器的最大大小?

c++ - 如何使用 include <algorithm> 中的 STL max 用于用户定义的数据类型

c++ - 从文件中读取数据并填充STL vector