Reputation: 2088
I'm a newbie to C++ and having an issue regarding std:map
with function pointers.
I have created a map
which has a string
as the key and stored a function pointer as the value. I faced a complication when I tried to use insert()
function to add a function pointer. However, it worked when I used []
operator. If you can, please explain this difference.
Here is a sample code I wrote.
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;
}
The Error says :
error: no matching function for call to 'std::map<std::basic_string<char>, void* (*)(void*)>::insert(std::string&, void* (*&)(void*))'
Even though I got this working (compiled) with the []
operator, I would like to know why I got an error when using insert()
.
Thank you.
Upvotes: 0
Views: 2044
Reputation: 3348
You insert elements into std::map using a std::pair of the key and value:
map.insert(std::make_pair(key,value));
Alternatively you can emplace values in c++11:
map.emplace(key,value);
The [] operator returns a reference to the value for the key passed in:
value_type &
And automatically constructs an element for that key if it doesn't already exist. Make sure you understand what the difference in behavior is between insert() and the [] operator before using them (the latter will replace existing values for a key for example).
See http://en.cppreference.com/w/cpp/container/map for more information.
Upvotes: 4