C++ 在C++;?
您能解释一下迭代器在以下代码中查找最大数和查找数字的机制吗C++ 在C++;?,c++,vector,iterator,C++,Vector,Iterator,您能解释一下迭代器在以下代码中查找最大数和查找数字的机制吗 #include "stdafx.h" #include <iostream> #include<vector> #include <string> #include <algorithm> #define n 3 using namespace std; class student{ public: void vrod(); void dis(); int st
#include "stdafx.h"
#include <iostream>
#include<vector>
#include <string>
#include <algorithm>
#define n 3
using namespace std;
class student{
public:
void vrod();
void dis();
int stno,score,i;
string name;
};
int main(){
int l,*find_score;
vector<student> my_vector;
for(int i = 0; i < n; i++)
{
student new_student;
cout << "Number: ";
cin >> new_student.stno;
cout << "Score: ";
cin >> new_student.score;
cout << "Name: ";
cin >> new_student.name;
my_vector.push_back(new_student);
}
int max_score = std::max_element(
my_vector.begin(),
my_vector.end(),
[] (student const& lhs, student const& rhs){
return lhs.score < rhs.score;
}
)->score;
cout<<max_score;
cout<<"l=";
cin>>l;
auto iter = std::find_if(my_vector.begin(), my_vector.end(),
[l] (student const& scores){ return scores.score ==l; });
if ( iter != my_vector.end())
cout<<"it is available"<<(*iter).name<<(*iter).stno;
else
cout<<"not available";
cin.get();
cin.get();
}
我想知道哪些数字将取代max_分数、lhs、rhs、my_vector.begin()、my_vector.end()、iter和*iter,以及max_元素和查找_的方法,如果它们基本上在数字上起作用并替换数字?
非常感谢您,首先,我建议您在询问有关std函数如何工作的问题之前,先查找在线参考资料。通过链接了解如何实现这些功能
查找传递给它的迭代器范围中最大的元素。同时传入函数时,它将使用函数而不是
运算符。是否尝试使用调试器?是。我运行这个程序,没有问题,但我不知道它是如何运行的。我在哪里暗示它不起作用?调试器将允许您在不同的执行步骤中检查变量的值。student.score
和max_score
应为float
s以存储值,如3.75,除非您希望存储375并稍后除以(100.0)。学生。我是干什么的?我目前没有关于迭代器的好的阅读材料。如果将指向数组的指针视为数组迭代器,可能会有所帮助。感谢您的回答,我对指针的定义没有任何问题。int=*p,m,s;m=5;p=&m;s=*p;但是,在这些程序中,我们只使用*而没有定义&as地址。为什么?我不能理解这件事!?迭代器定义其运算符*
以提供类似指针的接口。它们指向的地址在创建时定义。对于vector
,begin()
和end()
创建迭代器,并且很可能在其函数体中使用&来获取地址。还要注意,迭代器的行为可能与指针不完全一样。set
的迭代器具有operator++
,它将迭代器指向二进制搜索树中的下一个元素,而不是简单地递增地址。这是一种封装,允许程序员专注于高级概念(即我们获得的下一个元素),而不必担心实现细节(如何在树中找到下一个元素)。编写的指针可用于低级程序。那么,在面向对象程序中使用指针是常见的吗?
1 3 sam
2 3.5 larry
3 3.75 john
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&