Creating an alphabetic list using forward_list

430 Views Asked by At

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;
    }
}
1

There are 1 best solutions below

0
Chendra On

I think the trick is inside the loop you have to keep the iterator before moving to the next element. For example:

void insertOrdered(std::forward_list<int> &l, const Person& p) {
  if (l.empty()) {
    l.emplace_front(p);
    return;
  }
  for (auto i=l.begin(); i!= l.end();) {
    auto m = i; // keep the current iterator i to m.
    if (p < *i) {
      l.insert_after(i, *i);
      *i = p;
      return;
    }
    else {
      i++; // increase the iterator i
      if (i == l.end()) {       
        l.emplace_after(m,p); // use m to add data to the last element
        return;
      }
    }
  }
}