First you could flatten the vector. I used the code from https://stackoverflow.com/a/6404886/15388024:
#include <iterator>
#include <algorithm>
// COCiter == Container of Containers Iterator
// Oiter == Output Iterator
template <class COCiter, class Oiter>
void flatten (COCiter start, COCiter end, Oiter dest) {
while (start != end) {
dest = std::copy(start->begin(), start->end(), dest);
++start;
}
}
Then you can apply make_heap
with your comparison:
vector<vector<int>> arr = {{10, 2}, {4, 10}, {1, 4}, {11, 2}};
vector<int> flatArr;
flatten(arr.begin(), arr.end(), std::back_inserter(flatArr));
auto fn = [](int a, int b){
return a < b;
};
make_heap(flatArr.begin(), flatArr.end(), fn);
An example:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template <class COCiter, class Oiter>
void flatten (COCiter start, COCiter end, Oiter dest) {
while (start != end) {
dest = std::copy(start->begin(), start->end(), dest);
++start;
}
}
int main() {
std::vector<std::vector<int>> arr = {{10, 2}, {4, 10}, {1, 4}, {11, 2}};
std::vector<int> flatArr;
flatten(arr.begin(), arr.end(), std::back_inserter(flatArr));
auto fn = [](int a, int b){
return a > b;
};
std::make_heap(flatArr.begin(), flatArr.end(), fn);
for (const auto el : flatArr) {
std::cout << el << ' ';
}
}
with output:
11 10 10 2 1 4 4 2 // with heap property flatArr[(i + 1) / 2 - 1] >= flatArr[i]
// 11
// / \
// 10 10
// /\ /\
// 2 1 4 4
// /
// 2
Change the comparison function to
auto fn = [](int a, int b){
return a > b;
};
to get a min heap
1 2 4 2 10 4 11 10 // with min heap property flatArr[(i + 1) / 2 - 1] <= flatArr[i]
// 1
// / \
// 2 4
// / \ / \
// 2 10 4 11
// /
// 10