简体   繁体   English

为什么 std::sort 不要求用户指定模板类型?

[英]why does std::sort not require the user to specify the templated types?

If I understand correctly, in the Standard Library, there exists this definition of std::sort() :如果我理解正确,在标准库中,存在std::sort()的定义:

template< class RandomIt > 
constexpr void sort( RandomIt first, RandomIt last );

Suppose I have such a vector that I wish to sort:假设我有一个想要排序的向量:

std::vector<int> data {9, 7, 5, 3, 1};

If this is the case, then why can I just write:如果是这样,那我为什么只能写:

std::sort(data.begin(), data.end());

as opposed to requiring:而不是要求:

std::sort<std::vector<int>::iterator>(data.begin(), data.end());

If possible, could someone provide a generic explanation?如果可能的话,有人可以提供一个通用的解释吗? I think I've definitely seen more than one instance of this where the template type almost seems to be automatically deduced... or is it being automatically deduced...?我想我肯定已经看到不止一个这样的例子,其中模板类型几乎似乎是自动推导出来的……或者它是被自动推导出来的……?

or is it being automatically deduced...?还是自动推导...?

Yes.是的。

When a template parameter is used for a function parameter, the template argument can be deduced from the argument passed to the function. So, in this case RandomIt is deduced from the arguments data.begin() and data.end() .当模板参数用于 function 参数时,模板参数可以从传递给 function 的参数推导出来。因此,在这种情况下, RandomIt是从 arguments data.begin()data.end()推导出来的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM