0

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Got it, I miscalculated the ranges by one, and now I see why I did it. Funny part, I wrote exactly same code to make sure I am getting ranges, and still failed to perceive that 3 shouldn't be in 2 4 6 3.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.