【发布时间】: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);
}
但是,我尝试使用模板,我发现我不知道如何使用first和last来创建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