I have an algorithm and I'd like to translate my code so instead of using arrays I'd like to use vectors.
How would you translate this: (the side of b + j and a)
find_kth(a, b + j, i, size_b - j, k - j);
where
int find_kth(int a[], int b[], int size_a, int size_b, int k);
into
int find_kth(const vector<int>& a, const vector<int>& b, int size_a, int size_b, int k);
It must be equivalent so calls like this return the same value as if I were using arrays:
min(a[0], b[0]);
A standard way would be to use iterator ranges instead:
template <typename Iterator>
int find_kth(
Iterator a_begin,
Iterator a_end,
Iterator b_begin,
Iterator b_end,
int k);
This comes in handy, since you need to operate only on a section of a vector. You don't need to split the vector with this approach.
Improved signature based on SergeyA's comment:
template <typename T>
using is_fwd_it = std::is_base_of<
std::forward_iterator_tag,
typename std::iterator_traits<T>::iterator_category>;
template <typename A_It, typename B_It,
typename = typename std::enable_if<
is_fwd_it<A_It>::value && is_fwd_it<B_It>::value>::type>
int find_kth(
A_It a_begin,
A_It a_end,
B_It b_begin,
B_It b_end,
int k);
You can also add another template parameter, or use std::iterator_traits
to get the value_type
, instead of having int
.