使用 STL std::merge() 将向量的两个部分合并到另一个向量中

Merging two parts of the vector into another vector using STL std::merge()

本文关键字:向量 合并 两个 另一个 std STL merge 使用      更新时间:2023-10-16

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