newprint
newprint

Reputation: 7090

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

Have two vectors: std::vector<int> collA{2,4,6,3,5,7} & std::vector<int> collB(collA.size()), and I am trying to merge left half of collA(contains even numbers) with right side of collA(contains odd numbers) into 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 

However, std::merge() fails somewhere and Visual Studio 2012 gives me following error:

 ---------------------------
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.

Both Input ranges are sorted, so why am I getting this error ? (Note: VS2012 does not support C++11 initializer list syntax, I used to save some space)

Upvotes: 0

Views: 483

Answers (1)

awesoon
awesoon

Reputation: 33701

Both Input ranges are sorted

No, this is not true. You could check that with

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, " "));

Output:

2 4 6 3 
3 5 7 

You have to change last iterator for first sequence:

std::next(collA.cbegin(), collA.size()/2)
//                                     no + 1 here

Because size of collA is 6, and collA.cbegin() + collA.size() / 2 + 1 is the same as collA.cbegin() + 4 and points to 5.

Upvotes: 1

Related Questions