等价于c ++中vector上的int [] + k

Dan*_*pez 3 c++ arrays pointers vector array-view

我有一个算法,我想翻译我的代码,而不是使用数组,我想使用矢量.

你会如何翻译这个:( b + j和a的一面)

find_kth(a, b + j, i, size_b - j, k - j);
Run Code Online (Sandbox Code Playgroud)

哪里

int find_kth(int a[], int b[], int size_a, int size_b, int k);
Run Code Online (Sandbox Code Playgroud)

int find_kth(const vector<int>& a, const vector<int>& b, int size_a, int size_b, int k);
Run Code Online (Sandbox Code Playgroud)

它必须是等效的,所以像这样的调用返回相同的值,就像我使用数组一样:

min(a[0], b[0]);
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 5

使用功能模板:

template <typename Iterator>
int find_kth(Iterator a, Iterator b, int size_a, int size_b, int k)
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

您可以使用两种类型的迭代器使其更通用.

template <typename IteratorA, typename IteratorB>
int find_kth(IteratorA a, IteratorB b, int size_a, int size_b, int k)
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

这使您可以灵活地使用std::vector<int>for aintfor 数组,b反之亦然.

  • @DanielRocaLopez,看看[Iterator Concept](http://en.cppreference.com/w/cpp/concept/Iterator)和[C++算法库](http://en.cppreference.com/w/ CPP /算法).希望这些页面能够回答您的问题. (2认同)

Log*_*uff 5

标准方法是使用迭代器范围:

template <typename Iterator>
int find_kth(
    Iterator a_begin,
    Iterator a_end,
    Iterator b_begin,
    Iterator b_end,
    int k);
Run Code Online (Sandbox Code Playgroud)

这很方便,因为您只需要在矢量的一部分上操作.您不需要使用此方法拆分矢量.

根据SergeyA的评论改进了签名:

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);
Run Code Online (Sandbox Code Playgroud)

您还可以添加另一个模板参数,或者用于std::iterator_traits获取value_type,而不是具有int.

  • 虽然我做了upvote,但从技术上讲,你不需要两组迭代器属于同一类型.并且您希望它们是特定的迭代器 - 例如转发迭代器.所以你的find_kth可以改进:) (2认同)