使用 STL std::merge() 将向量的两个部分合并到另一个向量中
Merging two parts of the vector into another vector using STL std::merge()
有两个向量:std::vector<int> collA{2,4,6,3,5,7}
& std::vector<int> collB(collA.size())
,我正在尝试将collA
的左半部分(包含偶数)与collA
的右侧(包含奇数)合并为collB
:
std::merge(collA.cbegin(), std::next(collA.cbegin(), collA.size()/2 + 1), // left source
std::next(collA.cbegin(), collA.size()/2), collA.cend(), // right source
collB.begin()); // Output
但是,std::merge()
某处失败,Visual Studio 2012 给我以下错误:
---------------------------
Microsoft Visual C++ Runtime Library
---------------------------
Debug Assertion Failed!
Program: C:Windowssystem32MSVCP110D.dll
File: c:program files (x86)microsoft visual studio 11.0vcincludealgorithm
Line: 3102
Expression: sequence not ordered
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
两个输入范围都已排序,那么为什么我会收到此错误?(注意:VS2012不支持C++11初始化列表语法,我用来节省一些空间)
两个输入范围均已排序
不,这不是真的。你可以检查一下
std::vector<int> collA{2,4,6,3,5,7};
std::copy(collA.cbegin(), std::next(collA.cbegin(), collA.size()/2 + 1),
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
std::copy(std::next(collA.cbegin(), collA.size()/2), collA.cend(),
std::ostream_iterator<int>(std::cout, " "));
输出:
2 4 6 3
3 5 7
您必须更改第一个序列的最后一个迭代器:
std::next(collA.cbegin(), collA.size()/2)
// no + 1 here
因为collA
的大小是 6,collA.cbegin() + collA.size() / 2 + 1
与 collA.cbegin() + 4
相同并指向 5
.
相关文章:
- 将向量的 N 段合并到位C++
- 使用向量在 c++ 中合并排序实现
- 如何合并函数返回的向量?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- C++ 合并排序返回原始向量
- 如何修复错误:使用向量查找最小值和最大值进行合并排序
- C++ 使用向量实现合并排序
- 如何使用C++有效地合并排序与向量
- 使用 move::语义将大量向量合并为更大的向量
- 合并排序的合并操作无法使用 c++ 向量
- 如何在C 中合并两个向量
- 合并,分类和删除重复分类的向量和未分类的向量
- 使用STL算法合并2个向量
- 合并2个不同长度的向量并事先对它们进行排序,而无需排序函数
- 将函数两个向量合并为第三个向量
- 如何在C++中将排序的向量合并为单个向量
- 与C 中的向量合并
- 将两个排序向量合并到一个排序向量中
- 将子向量合并/展平为单个向量c++(将2d转换为1d)
- 将向量合并到现有向量中