2013-07-30 2 views
0

두 벡터가 병합되는 데 문제가 있습니다. 그들은 거의 작동하지 않아 합병 된 산출물을 얻습니다. 프로그램이 충돌하는 시간의 90 %. 저는 C++과 프로그래밍에 익숙하지 않습니다. 내가 사용하고있는 책은 C++ 게임 프로그래밍을 시작하는 것이다. 또한 Microsoft Visual C++ 2008을 사용하십시오.C++에서 두 목록을 병합하여 병합

여기 내 코드입니다.

//high scores 
//demonstartes algorithms 

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <ctime> 
#include <cstdlib> 

using namespace std; 

int main() 
{ 
    vector<int>::const_iterator iter; 
    cout << "creating a list of scores."; 
    vector <int> scores; 
    scores.push_back(1500); 
    scores.push_back(3500); 
    scores.push_back(7500); 


cout << "\nHight scores:\n"; 
for (iter = scores.begin(); iter != scores.end(); ++iter) 
    cout << *iter << endl; 

cout << "\nRandomizing scores."; 
srand(time(0)); 
random_shuffle(scores.begin(), scores.end()); 
cout << "\nHighs scores:\n"; 
for (iter = scores.begin(); iter != scores.end(); ++iter) 
    cout << *iter << endl; 

cout << "\nCreating another list fo scores."; 
vector<int> moreScores; 
moreScores.push_back(2000); 
moreScores.push_back(4000); 
moreScores.push_back(8000); 

cout << "\nMore High Scores:\n"; 
for (iter = moreScores.begin(); iter != moreScores.end(); ++iter) 
    cout << *iter << endl; 

cout << "\nMerging both lists."; 
vector<int> allScores(6); //need container big enough to hold results 
// allScores = null; //I tried to add a null statement to this so that memory would be clear. It didn't help. 
merge(scores.begin(),scores.end(), 
    moreScores.begin(),moreScores.end(), 
    allScores.begin()); 


cout << "\nAll Hight Scores:\n"; 
for (iter = allScores.begin(); iter != allScores.end(); ++iter) 
    cout << *iter << endl; 

return 0; 

} 

답변

1

병합 기능은 정렬 된 배열에 적용됩니다. 문제는 배열을 random_shuffle로 섞어 배열이 정렬되지 않을 가능성이 있다는 것입니다 (확률이 5/6 인 경우 약 90 %). 아마도 당신은 입력이 정렬되어 있는지 확인하는 디버그 주장을 잡았을 것입니다.

1

은 범위를 정렬해야합니다. 따라서 범위를 먼저 정렬해야합니다.

if (!std::is_sorted(scores.begin(), scores.end())) 
    std::sort(scores.begin(), scores.end()); 

if (!std::is_sorted(moreScores.begin(), moreScores.end())) 
    std::sort(moreScores.begin(), moreScores.end()); 

std::merge(scores.begin(),scores.end(), 
      moreScores.begin(),moreScores.end(), 
      allScores.begin()); 
관련 문제