【问题标题】:How to use a pair of iterators [first, last) to create a container in the template?如何使用一对迭代器 [first, last) 在模板中创建容器?
【发布时间】:2015-12-02 00:37:18
【问题描述】:

我写了一个MergeSort函数,下面是它的声明:

void MergeSort(
    std::vector<int>::iterator first,
    std::vector<int>::iterator last) {
  // Get the same size as nums, so we can use some stable iteartors later.
  std::vector<int> tmp_vector(last - first);
  Sort(first, last, tmp_vector.begin());
  std::copy(tmp_vector.begin(), tmp_vector.end(), first);
}

但是,我尝试使用模板,我发现我不知道如何使用firstlast来创建tmp_vector,而我只知道RandomIterator的类型:

template <typename RandomIterator>
void MergeSort(
    RandomIterator first,
    RandomIterator last) {
  // Get the same size as nums, so we can use some stable iteartors later.
  // How to create tmp_vector?
  mergesort::Sort(first, last, tmp_vector.begin());
  std::copy(tmp_vector.begin(), tmp_vector.end(), first);
}

据说it is not possible to get the type of the container of the iterators,有什么想法吗?谢谢!

【问题讨论】:

  • 您首先需要将容器类型作为模板参数。
  • 迭代器后面甚至可能没有容器。

标签: c++ templates iterator containers


【解决方案1】:

您可以创建迭代器的 value_type 向量。这不是原始容器类型,但它会为您提供所需的临时容器。

【讨论】:

  • 或者更好地使用std::iterator_traits&lt;RandomIterator&gt;::value_type,如果RandomIterator实际上是一个指针。
猜你喜欢
  • 2012-08-03
  • 1970-01-01
  • 2021-01-09
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多