使用merge合并C ++中的两个列表

时间:2013-07-30 06:57:57

标签: c++ arrays vector merge

我无法让我的两个向量合并。他们很少工作我得到合并的输出。 90%的程序崩溃了。我是C ++和编程的新手。我正在使用的书正在开始C ++游戏编程。还使用Microsoft Visual C ++ 2008。

这是我的代码。

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

}

2 个答案:

答案 0 :(得分:1)

合并函数应该与排序数组一起使用。问题是当你使用random_shuffle对数组进行混洗时,你的数组很可能没有排序(概率为5/6,大约是90%)。可能你遇到了一个调试断言,它检查输入是否已排序。

答案 1 :(得分: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());