Homework Help Question & Answers

c++ 10. Code the template function merge, which merges two ranges into a single output container. The first two argu- ments indicate one range and the next two indicate the other range. The last argu...

c++

10. Code the template function merge, which merges two ranges into a single output container. The first two argu- ments indic

10. Code the template function merge, which merges two ranges into a single output container. The first two argu- ments indicate one range and the next two indicate the other range. The last argument is a container witha push back function. The input ranges are sorted into ascending order and operatorc is available to compare el- ements of these ranges. The output container should also be sorted into the same order. If an element from one container is equal to an element in the other container, the order of output is not important. [3v] template void merge (itor beginl, itor endl, itor begin2, itor end2, containers out)
0 0
Next > < Previous
ReportAnswer #1

Possible implementation

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);
}

Second version

template<class InputIt1, class InputIt2,
         class OutputIt, class Compare>
OutputIt merge(InputIt1 first1, InputIt1 last1,
               InputIt2 first2, InputIt2 last2,
               OutputIt d_first, Compare comp)
{
    for (; first1 != last1; ++d_first) {
        if (first2 == last2) {
            return std::copy(first1, last1, d_first);
        }
        if (comp(*first2, *first1)) {
            *d_first = *first2;
            ++first2;
        } else {
            *d_first = *first1;
            ++first1;
        }
    }
    return std::copy(first2, last2, d_first);
}
Add Homework Help Answer
Add Answer of:
c++ 10. Code the template function merge, which merges two ranges into a single output container. The first two argu- ments indicate one range and the next two indicate the other range. The last argu...
Your Answer: Your Name: What's your source?
Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
More Homework Help Questions Additional questions in this topic.
Need Online Homework Help?
Ask a Question
Get FREE Expert Answers
WITHIN MINUTES
Related Questions