2013-07-30 107 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

std::merge要求範圍進行排序。所以你需要確保範圍先排序。

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());