C ++ передать карту по ссылке в функцию - PullRequest
12 голосов
/ 14 октября 2011

Как я могу передать map на reference в функцию?Visual Studio 2010 выдает ошибку unresolved externals.В настоящее время у меня есть следующий упрощенный код:

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
}

Здесь есть несколько ответов на подобные вопросы, но они используют typedef и добавляют std:: в начале определения, но ядействительно не знаю, почему.

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;
}

Ошибка, которую я получил:

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> > > &)" (?analyzePlay@ComputerPlayer@@QAEHHVBoard@@AAV?$map@HHU?$less@H@std@@V?$allocator@U?$pair@$$CBHH@std@@@2@@std@@@Z) referenced in function "public: int __thiscallComputerPlayer::getBestMoves(void)" (?getBestMoves@ComputerPlayer@@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

1 Ответ

27 голосов
/ 14 октября 2011

Две вещи:

  • Добавьте #include<map> вверху и используйте std::map вместо map.
  • Определить function2 выше function1 Или хотя бы объявить function2 выше function1.

Вот как это должно быть сделано:

#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
}

Также обратите внимание, что избегайте new как можно больше. Используйте автоматические переменные по умолчанию, если только у вас нет веских причин не использовать их.

Автоматические переменные работают быстро, а код выглядит аккуратно и чисто. С ними проще писать код, исключающий исключение.

EDIT:

Теперь, когда вы опубликовали ошибку, вы также поняли, что

Я забыл добавить класс, частью которого являлась функция, в его начало. как в: Player :: function2 (std :: map & temp_map) {}

, как вы сказали в комментарии.

Хорошо, что ты сам это понял. Но, тем не менее, всегда сообщайте об ошибке в самом первом сообщении, когда вы задаете вопрос. Запомни это.

...