有两个 vector :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:\Windows\system32\MSVCP110D.dll
File: c:\program files (x86)\microsoft visual studio 11.0\vc\include\algorithm
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初始化列表语法,我用的是为了省点空间)
最佳答案
Both Input ranges are sorted
不,这不是真的。你可以用
检查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
。
关于c++ - 使用 STL std::merge() 将 vector 的两个部分合并到另一个 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19698567/