c++ - 使用 STL std::merge() 将 vector 的两个部分合并到另一个 vector 中

标签 c++ c++11 stl

有两个 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 + 1collA.cbegin 相同() + 4 并指向 5

关于c++ - 使用 STL std::merge() 将 vector 的两个部分合并到另一个 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19698567/

相关文章:

c++ - 无法捕获模板特化方法抛出的异常

c++ - 如何在 invokeMethod 函数中将列表、 vector 或数组作为参数传递

c++ - 在 C++11 中使用一个随机引擎进行多分布

c++ - 使用 std::vector 的奇怪段错误

c++ - STL 容器的迭代器是静态变量吗?

c++ - 预测可能的匹配以避免使用 Levenshtein 算法

c++ - 不同处理器中的不同输入参数

c++ - 将字符串和整数散列在一起?

C++ 代码 : What is wrong in this?

c++ - Qt 与 STL 和 Boost 配合得好吗?