简体   繁体   English

C ++中的通用模板

[英]Generic Templates in C++

I don't understand the answers to the following questions: 我不理解以下问题的答案:

Write a C++ function find_elem that takes two iterators first and last of some sequence of elements of type T and an object obj of type T. It returns the iterator to the first occurrence of obj in the range [first, last), or the iterator last if obj is not in the sequence. 编写一个C ++函数find_elem,它使用两个迭代器,它们分别是T类型的某些元素序列和T类型的对象obj的最后一个和最后一个。它将迭代器返回到[first,last)范围内的obj的第一个匹配项,或迭代器如果obj不在序列中,则返回last。

This was the answer 这就是答案

template <typename It, typename T>
It find_elem(It first, It last, const T & obj) {
   while (first != last && (*first) != obj) // I DON'T UNDERSTAND THIS LINE
   ++first;
   return first;
}

I dont understand the following line while (first != last && (*first) != obj) . 我不理解以下行, while (first != last && (*first) != obj) Why is it (*first != obj) when the questions asks you to return the iterator with the first instance of obj . 当问题要求您返回带有obj第一个实例的迭代器时,为什么是(*first != obj) I also don't get the following line ++first as in why you are incrementing the iterator first 我也没有首先得到下面的++first行,因为为什么你first增加迭代器

The ++first is executed by the while loop. ++ first由while循环执行。 I would write use { } here to make it clearer: 我在这里写use {}使其更清楚:

while (first!=last && (*first)!=obj) {
   ++first;
}

So, the while loop checks if (*first)==obj. 因此,while循环检查(* first)== obj。 If not, then it moves to the next element in the list using ++first, which increments the iterator. 如果不是,则使用++ first移至列表中的下一个元素,这将增加迭代器。 Then it ends either when first==last (meaning that we have gone through the entire list), or when (*first)==obj, meaning that we found what we were looking for. 然后,当first == last(意味着我们已经遍历整个列表)时,或者当(* first)== obj,这意味着我们找到了要寻找的东西时,它结束了。

A copy of first is passed to the function. first副本传递给该函数。 This means that the function can safely modify the variable by using it also to iterate the sequence. 这意味着该函数可以通过迭代访问序列来安全地修改变量。

It's just a concise alternative for the following code: 它只是以下代码的简洁替代方案:

template <typename It, typename T>
It find_elem(It first, It last, const T & obj) {
   It iterator = first;
   while (iterator != last && (*iterator) != obj)
   ++iterator;
   return iterator;
}

By the way... "generic templates" sounds strange, because templates are always generic. 顺便说一下,“通用模板”听起来很奇怪,因为模板始终是通用的。 I suppose template template parameters could be called "generic templates", though. 我想模板模板参数可以被称为“通用模板”。

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

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