0

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.