'Sort vector of vector using generic function
I'm trying to make a function which will sort rows of vector of vector using std::sort function from algorithm library. Function must be generic. And comparison criterion is sum of row elements. Function for comparing which will be used in std::sort function also must be generic.
EXAMPLE
2 5 1 3 4
9 8 9
3 3 2 3
4 5 2 1 1 3 2
After sorting:
9 8 9
4 5 2 1 1 3 2
2 5 1 3 4
3 3 2 3
#include <iostream>
#include <vector>
#include <algorithm>
template<typename tip>
auto Compare(std::vector<tip>&a, std::vector<tip>&b) {
auto sum_a = 0, sum_b = 0;
for (int i = 0; i < a.size(); i++)
sum_a += a[i];
for (int i = 0; i < b.size(); i++)
sum_b += b[i];
return sum_a > sum_b;
}
template <typename tip>
void sort_sum_of_rows(std::vector<std::vector<tip>> &mat) {
std::sort(mat.begin(), mat.end(), Compare);
}
int main() {
std::vector<std::vector<int>> a{{2, 5, 1, 3, 4},
{9, 8, 9},
{3, 3, 2, 3},
{4, 5, 2, 1, 1, 3, 2}};
sort_sum_of_rows(a);
for (auto &v : a) {
for (int j : v)
std::cout << j << " ";
std::cout << std::endl;
}
return 0;
}
ERRORS (line 15):
no matching function for call to ‘sort(std::vector >::iterator, std::vector >::iterator, )’
template argument deduction/substitution failed: main.cpp:15:12: note: candidate expects 2 arguments, 3 provided
Could you help me to fix my function Compare?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
