2011-10-14 11 views
10

¿Cómo puedo pasar un map por reference en una función? Visual Studio 2010 me está dando un error unresolved externals. Actualmente, tengo el siguiente código simplificado:C++ pase un mapa por referencia a la función

void function1(){ 
    map<int, int> * my_map = new map<int, int>(); 
    function2(*my_map); 
} 

void function2(map<int, int> &temp_map){ 
    //do stuff with the map 
} 

Hay algunas respuestas a preguntas similares aquí, pero ellos hacen uso de typedef y añadiendo std:: al principio de la definición, pero realmente no estoy seguro de por qué.

int ComputerPlayer::getBestMoves(){ 
    //will return the pit number of the best possible move. 

    //map to hold pit numbers and rankings for each possible pit number. 
    //map<pitNumber, rank> only adds pit numbers to map if they have seeds in them. 

    std::map<int, int> possiblePits; //map 
    std::map<int, int>::iterator it; //iterator for map 
    for(int index = 1; index <= getBoardSize(); index++){ 
     if(_board.getPitValue(index) > 0){ 
      possiblePits.insert(pair<int, int>(index, 0)); 
     } 
    } 

    int tempBoardSize = _board.getBoardSize(); 

    //loop that will analyze all possible pits in the map 
    for(it = possiblePits.begin(); it != possiblePits.end(); it++){ 
     Board tempBoard = _board; 
     int pitNum = it->first; 

     int score = analyzePlay(pitNum, tempBoard, possiblePits); 
    } 
    return 0; 
} 

int analyzePlay(int pitNum, Board tempBoard, std::map<int, int> &possibleMoves){ 
    int tempBoardSize = tempBoard.getBoardSize(); 
    int tempSeeds = tempBoard.getPitValue(pitNum); 
    int lastPitSown; 

    tempBoard.setPitToZero(pitNum); 

    for(int index = 1; index <= tempSeeds; index++){ 

     if(pitNum == tempBoardSize * 2 + 1){ 
      //skips over human's score pit 
      pitNum += 2; 
      lastPitSown = pitNum; 
      tempBoard.incrementPit(pitNum); 
     } 
     else{ 
      pitNum++; 
      lastPitSown = pitNum; 
      tempBoard.incrementPit(pitNum); 
     } 
    } 

    if(tempBoard.getPitValue(lastPitSown) == 1 && lastPitSown >= tempBoardSize + 2 && lastPitSown <= tempBoardSize * 2 + 1){ 
     //turn ends. last seed sown into empty pit on opponent side. 

    } 
    else if(tempBoard.getPitValue(lastPitSown) > 1 && lastPitSown != tempBoardSize + 1){ 
     //keep playing with next pit. last seed was sown into non-empty pit. 

    } 
    else if(lastPitSown == tempBoardSize + 1){ 
     //extra turn. last seed sown into score pit. 

    } 
    else if(tempBoard.getPitValue(lastPitSown) == 1 && lastPitSown != tempBoardSize + 1 && lastPitSown <= tempBoardSize && lastPitSown >= 1){ 
     //turn ends. last seed sown into empty pit on your side. capture. 


    } 
    return 0; 
} 

El error que estaba recibiendo:

Error 1 error LNK2019: unresolved external symbol "public: int __thiscall ComputerPlayer::analyzePlay(int,class Board,class std::map<int,int,struct std::less<int>,class std::allocator<struct std::pair<int const ,int> > > &)" ([email protected]@@[email protected]@[email protected][email protected]@[email protected]@[email protected][email protected][email protected]@@@[email protected]@[email protected]@@Z) referenced in function "public: int __thiscallComputerPlayer::getBestMoves(void)" ([email protected]@@QAEHXZ) C:\Users\Josh\Dropbox\Congkak_2\Congkak_2\ComputerPlayer.obj 
Error 2 error LNK1120: 1 unresolved externals C:\Users\Josh\Dropbox\Congkak_2\Debug\Congkak_2.exe 
+0

Los errores externos no resueltos significan errores de enlace. No creo que tenga nada que ver con pasar el mapa por referencia a una función; es más probable que se trate de un error de sintaxis. – Ayjay

+0

Además, ese código funciona cuando lo ejecuto. Es probable que tenga su configuración de proyecto configurada incorrectamente. – Ayjay

Respuesta

23

dos cosas:

  • Añadir #include<map> en la parte superior, y el uso std::map en lugar de sólo map.
  • Defina function2 anterior function1 O al menos declare function2 sobre function1.

Así es como tanto se debe hacer:

#include<map> 

void function2(std::map<int, int> &temp_map); //forward declaration 

void function1(){ 
    std::map<int, int> my_map; //automatic variable 
           //no need to make it pointer! 
    function2(my_map); 
} 

void function2(std::map<int, int> &temp_map){ 
    //do stuff with the map 
} 

También tenga en cuenta que evitan new tanto como sea posible. Utilice variables automáticas de forma predeterminada, a menos que tenga una razón muy fuerte para no usarlo.

Las variables automáticas son rápidas, y el código se ve pulcro y limpio. Con ellos, es más fácil escribir código de excepción.

EDIT:

Ahora que usted envió el error, también se dio cuenta de que,

me olvidó añadir la clase que la función era parte de hasta el comienzo de la misma. como en: Jugador :: function2 (std :: mapa < int, int> & temp_map) {}

, como usted ha dicho en el comentario.

Está bien que lo haya descubierto usted mismo. Pero aún así, siempre publique el error en su primera publicación, cuando haga la pregunta. Recuerda esto.

+0

También podría simplemente poner function2 sobre function1 ... – Ayjay

+0

Bien, estoy bastante seguro de que he cambiado lo que necesitaba, pero todavía estoy obteniendo el error externo no resuelto. Editaré mi publicación original con el código que estoy usando en mi programa en un minuto. – Cuthbert

+1

@ d2jxp: ¿Por qué no publica el error junto con más código? ¿Cómo se supone que debemos saber exactamente cuál es el error? – Nawaz

Cuestiones relacionadas