36
loading...
This website collects cookies to deliver better user experience
merge
inplace_merge
std::merge
takes two sorted input ranges, merges them and returns an iterator that points past the last copied element.begin()
and end()
iterators of the first range, then the begin()
and end()
iterators of the second range.merge
will not take care of sorting its inputs.auto results = std::vector<int>(input1.size() + input2.size());
std::back_inserter()
. That will also take care of the job.merge
correctly:#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector nums {1, 3, 5, 8, 9};
std::vector otherNums {2, 4, 6, 7, 10};
std::vector<int> results;
std::merge(nums.begin(), nums.end(), otherNums.begin(), otherNums.end(), std::back_inserter(results));
for(auto n: results) {
std::cout<< n << ' ';
}
std::cout << '\n';
}
/*
1 2 3 4 5 6 7 8 9 10
*/
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector nums {1, 3, 5, 8, 9};
std::vector unsortedNums {4, 2, 10, 7, 6};
std::vector<int> results;
std::merge(nums.begin(), nums.end(), unsortedNums.begin(), unsortedNums.end(), std::back_inserter(results));
for(auto n: results) {
std::cout<< n << ' ';
}
std::cout << '\n';
}
/*
1 3 4 2 5 8 9 10 7 6
*/
inplace_merge
takes two sorted ranges which are connected! As the documentation says, they must be consecutive and as a result, the whole range will be sorted.inplace_merge
takes 3 parameters.merge
, inplace_merge
can take an optional comparator as a fourth parameter and it also might an execution policy (since C++17) before all the other parameters.#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector nums {1, 3, 5, 8, 9, 2, 4, 6, 7, 10};
std::inplace_merge(nums.begin(), nums.begin()+5, nums.end());
for(auto n: nums) {
std::cout<< n << ' ';
}
std::cout << '\n';
}
/*
1 2 3 4 5 6 7 8 9 10
*/
nums.begin()+5
the first sorted range containing elements 1, 3, 5, 8, 9
end and another sorted subrange 2, 4, 6, 7, 10
starts. As a result of inplace_merge
, the full container is merged.merge
and inplace_merge
algorithms. We saw how to merge two sorted containers into one and also how to merge two consecutive sorted ranges into one. 36