用merge在C++中合并两个列表
Merging both lists in C++ with 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;
}
merge函数应该用于排序数组。问题是,当你用random_shuffle打乱你的数组时,你的数组很可能没有排序(概率为5/6,约为90%)。可能您捕获了一个调试断言,该断言检查输入是否已排序。
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());
相关文章:
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 我如何创建一个列表,然后从中创建两个列表,其中一个用于偶数,另一个用于奇数?
- 如何在两个列表中比较和获取非包含值
- 将两个列表合并为一个蛇形列表
- 使用特征查找两个列表之间的差异
- c 中的两个列表在o(1)复杂性中
- 关于合并两个列表的算法的一些问题
- 特殊使用功能 - 两个列表的产品
- 如何获取两个列表的公共元素并将其存储在新列表中而不会重复
- 使用两个列表中的组合生成函数调用
- (C++)如何创建一个函数来接收两个排序的链表并返回出现在两个列表中的第三个元素列表
- 从两个列表中随机配对
- 在有限边界下有效地合并两个列表
- 用c++合并两个列表
- 用merge在C++中合并两个列表
- 核对两个列表
- 读取Txt文件,逐行,在两个列表中存储多个类型,如果存在的话
- 在两个列表中匹配元素算法
- 比较两个列表并查找缺失元素的有效方法
- 如何在C++中应用两个列表之间的交集