I have a linked list of students. Each node in my list has a pointer to a student object which contains the data for that student. I wrote a function that deletes every student with a specified name.
This is my first time ever making a linked list, and, although I got the function working, I wonder if there is a more efficient way to do it (my code seems a little too convoluted).
You guys definitely have a lot more experience than I do with this, and I was wondering if you could look over my code and see if there are any obvious ways to make it more efficient.
I probably won't help you with your function (seems like there's a class called Node which I don't know of), but why not try using something that's already thoroughly tested and secure?
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
int main()
{
std::list<std::string> students
{
"Clara",
"John",
"ABCD",
"Curry",
"Strawberry",
"SugarSpice"
};
std::string who = "ABCD";
std::list<std::string>::iterator it = std::remove_if(students.begin(),
students.end(),
[&who](const std::string &name)
{
return name == who;
});
students.erase(it, students.end());
for (auto &x : students)
std::cout << x << std::endl;
return 0;
}
std::remove_if on a list moves all items to be deleted to the back of the container, and returns an iterator to the first element that's supposed to be deleted.
From that element (it), we traverse towards students.end(), deleting everything in between.