I'm reviewing STL Algorithms. So I've written some algorithms among which this one merge_
:
template <typename InIt1, typename InIt2, typename OutIt>
OutIt merge_(InIt1 first1, InIt1 last1, InIt2 first2, InIt2 last2, OutIt dest){
while(first1 != last1){
if(first2 == last2)
return copy(first1, last1, dest);
*dest++ = *first1 < *first2 ? *first1++ : *first2++;
}
return copy(first2, last2, dest);
}
int main(){
int a[]{1, 3, 5, 7};
int b[]{2, 4, 10, 12};
vector<int> v(10, 0);
// 1 2 3 4 5 7 10 12
//merge(begin(a), end(a), begin(b), end(b), v.begin());
merge_(begin(a), end(a), begin(b), end(b), v.begin());
for(int i : v)
cout << i << ", ";
cout << '\n';
std::cout << "\ndone!\n";
}
It works just fine however I saw a possible implementation on cppreference: https://en.cppreference.com/w/cpp/algorithm/merge this way:
First version template<class InputIt1, class InputIt2, class OutputIt> OutputIt merge(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first) { for (; first1 != last1; ++d_first) { if (first2 == last2) { return std::copy(first1, last1, d_first); } if (*first2 < *first1) { *d_first = *first2; ++first2; } else { *d_first = *first1; ++first1; } } return std::copy(first2, last2, d_first); }
I don't know why such complicated logic?