Insert pair into map in c++

2019-07-20 09:01发布

问题:

I have the following map structure:

std::map<std::pair<int, char>, int> transitions;

That represent the transition of the nondeterministic automaton, each with 2 integers and a character, I, J and C, representing the states where the transition, ie, the transition goes from state i to state J with the character C.

0 0 a
0 1 a
1 1 b
1 2 c
1 3 c
3 4 d
4 4 d
4 5 d

I wish to insert into it. How I can do?

I thought about doing the following:

typedef map<pair<int, char>, int> transitions;
    for (j=0; j<numberTransitions;j++)
    {

        cin>> stateOrigin>>stateDestination>>transitionCharacter;
        transitions.insert(transitions::value_type(std::make_pair(stateOrigin,transitionCharacter), stateDestination ));

    }

I do not think that is the way to do it, I am newbie using the map library.

回答1:

The only thing I see wrong is you need an object:

    transitions.insert(transitions::value_type(std::make_pair(stateOrigin,transitionCharacter), stateDestination ));
    ^^^^^^^^^^^   is a type


    /// Should be 
    transitions   trans;

    // Then later in the loop.
    trans.insert(transitions::value_type(std::make_pair(stateOrigin,transitionCharacter), stateDestination ));

You could even take it a step further and use key_type rather than make pair:

trans.insert(transitions::value_type(transitions::key_type(stateOrigin,transitionCharacter), stateDestination ));

// or
for(/*STUFF*/)
{
    typedef transitions::value_type  value_type;
    typedef transitions::key_type    key_type;
    trans.insert(value_type(key_type(stateOrigin,transitionCharacter), stateDestination ));
}