I have been trying to code a program where I input data for a student class(with (const string &first_name, const string &last_name, float gpa, int id), that can display which students have a gpa above 1.00. I am having trouble iterating through a vector. Here is the function causing me trouble:
vector<Student> find_failing_students(vector<Student> &students) {
vector<Student> failing_students;
int endVar;
vector<Student>::iterator it;
std::vector<Student>::iterator &forwardmarch = &students.begin();
while(forwardmarch != &students.end())
{
Student temp = Student(forwardmarch->first_, forwardmarch->last_, forwardmarch->gpa_, forwardmarch->id_);
if(temp.getgpa(temp) < 1) {
failing_students.push_back(temp);
forwardmarch++;
}
the std::vector<Student>::iterator &forwardmarch = &students.begin();
part is giving me the following error: invalid initialization of non-const reference of type 'std::vector::iterator&' {aka '__gnu_cxx::__normal_iterator >&'} from an rvalue of type 'std::vector::iterator*' {aka '__gnu_cxx::__normal_iterator >*'}
the while loop while(forwardmarch != &students.end())
also gives me the following error: no match for 'operator!=' (operand types are 'std::vector::iterator' {aka '__gnu_cxx::__normal_iterator >'} and 'std::vector::iterator*' {aka '__gnu_cxx::__normal_iterator >*'})
I have tried many things and also tried using a more typical for loop too, one like
for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
it->doSomething();
}
Im a little confused and am pretty new to C++, any help would be appreciated. Thanks!
This line makes no sense:
std::vector<Student>::iterator &forwardmarch = &students.begin();
On the left side, the ampersand tells that you are declaring an object reference (not an object). On the right side, the ampersand tells to obtain a pointer to the object, instead of the object itself. The correct use is to declare a new object and assign it directly:
std::vector<Student>::iterator forwardmarch = students.begin();
This is very fundamental stuff. The reading topic would be pointers and references in C++.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.