I need to make a template function that takes 2 std::array
s with different sizes, but I don't know how to call it from the main
function:
// write a function to combine two sorted arrays and keep the resulting array sorted
#include<iostream>
#include<array>
using namespace std;
template <class T, size_t size>
template <class T, size_t size_1>
template <class T, size_t size_2>
array<T, size> combine(array<T, size_1> a, array<T, size_2> b)
{
int i, j, k;
i = j = k = 0;
array<T, size> c;
while (i < size_1 && k < size_2) {
if (a[i] < b[k]) {
c[j] = a[i];
j++;
i++;
} else {
c[j] = b[k];
j++;
k++;
}
}
if (i < size_1) {
for (int q = j; q < size_1; q++)
c[j] = a[q];
} else {
for (int e = k; e < size_2; q++)
c[j] = b[e];
}
return c;
}
int main()
{
std::array<int, 5> a = { 2, 5, 15, 18, 40 };
std::array<int, 6> b = { 1, 4, 8, 10, 12, 20 };
std::array<int, 11> c;
c = combine<int>(a, b);
for (int i = 0; i < c.size(); i++) {
cout << c[i];
}
return 0;
}
What you are trying to do is pass in two array
s with different sizes, and return an array
whose size is the sum of the two sizes.
You can declare your function this way:
template <typename T, std::size_t X, std::size_t Y>
std::array<T, X+Y> combine (std::array<T, X> a, std::array<T, Y> b)
{
//...
}
This way, template function argument deduction will work. So, you can avoid using explicit template parameters to call the function.
std::array<int, 5> a = { 2, 5, 15, 18, 40 };
std::array<int, 6> b = { 1, 4, 8, 10, 12, 20 };
auto c = combine(a, b);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.