gpt4 book ai didi

c++ - 迭代器的模板参数 : function infers type when called?

转载 作者:行者123 更新时间:2023-11-28 04:08:38 25 4
gpt4 key购买 nike

在 std::inplace_merge 上的页面中 cppreference.com ,它给出了使用 inplace_merge 进行合并排序的示例。我的问题与他们使用迭代器类型的模板参数实现合并排序的方式有关。

当它在主函数中调用 merge_sort 时,没有传入任何参数来告诉我们正在使用哪种迭代器。但是我已经编译了这段代码并且运行良好。为什么您不必告诉 merge_sort 我们正在使用哪种迭代器?你会怎么做?

#include <vector>
#include <iostream>
#include <algorithm>

template<class Iter>
void merge_sort(Iter first, Iter last)
{
if (last - first > 1) {
Iter middle = first + (last - first) / 2;
merge_sort(first, middle);
merge_sort(middle, last);
std::inplace_merge(first, middle, last);
}
}

int main()
{
std::vector<int> v{8, 2, -2, 0, 11, 11, 1, 7, 3};
merge_sort(v.begin(), v.end()); // <----------------- ?
for(auto n : v) {
std::cout << n << ' ';
}
std::cout << '\n';
}

最佳答案

发生这种情况是因为 Template argument: deduction

In order to instantiate a function template, every template argument must be known, but not every template argument has to be specified. When possible, the compiler will deduce the missing template arguments from the function arguments. This occurs when a function call is attempted, when an address of a function template is taken, and in some other contexts.

关于c++ - 迭代器的模板参数 : function infers type when called?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58263556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com