在 std::map 中使用函数指针

Using function pointers in std::map

我是 C++ 的新手,遇到有关 std:map 函数指针的问题。

我创建了一个 map,它有一个 string 作为键,并存储一个函数指针作为值。当我尝试使用 insert() 函数添加函数指针时,我遇到了麻烦。但是,当我使用 [] 运算符时它起作用了。如果可以,请解释一下这个区别。

这是我写的示例代码。

OperatorFactory.h

#ifndef OPERATORFACTORY_H
#define OPERATORFACTORY_H

#include <string>
#include <map>

using namespace std;

class OperatorFactory
{
    public:
        static bool AddOperator(string sOperator, void* (*fSolvingFunction)(void*));
        static bool RemoveOperator(string sOperator);
        static void RemoveAllOperators();

    private:
        static map<string , void* (*) (void*)> map_OperatorMap;
};

// Static member re-declaration
map<string, void* (*) (void*)>  OperatorFactory::map_OperatorMap;

#endif // OPERATORFACTORY_H

OperatorFactory.cpp

#include "OperatorFactory.h"

void OperatorFactory::RemoveAllOperators()
{
    map_OperatorMap.clear();
}

bool OperatorFactory::RemoveOperator(string sOperator)
{
    return map_OperatorMap.erase(sOperator) != 0;
}

bool OperatorFactory::AddOperator(string sOperator, void* (*fSolvingFunction)(void*))
{
    // This line works well.
    map_OperatorMap[sOperator] = fSolvingFunction;

    // But this line doesn't.
    // map_OperatorMap.insert(sOperator, fSolvingFunction); // Error
    return true;

}

错误说:

error: no matching function for call to 'std::map<std::basic_string<char>, void* (*)(void*)>::insert(std::string&, void* (*&)(void*))'

尽管我使用 [] 运算符使它工作(编译),但我想知道为什么在使用 insert().

时出现错误

谢谢。

您使用键和值的 std::pair 将元素插入 std::map:

map.insert(std::make_pair(key,value));

或者,您可以在 c++11 中放置值:

map.emplace(key,value);

[] 运算符 returns 对传入的键的值的引用:

value_type & 

并自动为该键构建一个元素(如果它尚不存在)。在使用它们之前,请确保您了解 insert() 和 [] 运算符之间的行为差​​异(例如,后者将替换键的现有值)。

有关详细信息,请参阅 http://en.cppreference.com/w/cpp/container/map