请您解释迭代器的机制,以便在以下代码中找到最大数字和查找数字?
1 3 sam
2 3.5 larry
3 3.75 john
您认为我分别输入数字,分数和名称,如下所示:
minifyEnabled true
我想知道哪些数字代替max_score,lhs,rhs,my_vector.begin(),my_vector.end(), iter 和 * iter 以及max_element和find_if如何工作并基本上用数字替换数字? 非常感谢,
答案 0 :(得分:0)
首先,我建议在询问有关std
功能如何工作的问题之前查找在线参考。点击cppreference.com的链接,了解如何实施这些内容。
std::max_element
找到传递给它的迭代器范围中的最大元素。当传入函数时,它将使用函数而不是operator<
进行比较。在您的情况下,它会向具有最高分数的学生返回迭代器。
std::find_if
返回满足所提供谓词的第一个元素。在您的情况下,它会返回第一个有score == l
的学生。
此外,迭代器不会替换其内容。迭代器只是指向其底层元素的指针。
为了回答你的问题:
max_score = 3.75 // Note this is impossible because score is int
lhs and rhs students that are compared, and would depend on the implementation of max_element
Suppose max_element has a max_itr internally, one possibility is:
max_itr points to Sam at first
Then, lhr is Sam and rhs is Larry, comparison returns true. max_itr points to Larry.
Then, lhr is Larry and rhs is John, comparison returns true. max_itr points to John.
max_itr == end, return max_itr
my_vector.begin() returns an iterator pointing to Sam
my_vector.end() returns an iterator pointing to the end of vector, a non-existing element
iter is an iterator pointing to John (Because his score is equal to max_score)
iter* is John as student&