I am trying to create an alpabethic sorted list with a forward_list. The plan is to compare all elements to the element I want to insert into the list, and insert it if it is larger then an element. But the problem is that I cannot figure out a way to insert an element after the last element. I have googled it, and I only get answers saying that I should avoid the forward_list...
So the question is, how can I make this work...
void insertOrdered(std::forward_list<Person> &l, const Person& p) {
auto i = l.begin();
if (l.empty()) {
//placing an element at the front if the list is empty
l.emplace_front(p);
return;
}
for (i; i != l.end(); ) {
if (p < *i) {
//Moving the element at position i to the position after i.
l.insert_after(i, *i);
//placing person at i
*i = p;
return;
}
else{
i++;
}
}
//Trying to insert after the last element
l.emplace_front(l.end(), p);
}
Implementation of < operator:
bool Person::operator<(Person& rhs) {
if (this->firstname < rhs.firstname) {
return true;
}
else {
return false;
}
}
I think the trick is inside the loop you have to keep the iterator before moving to the next element. For example: